我目前有一个表,其中包含一个 ID 以及该 ID 字段的条件计数。例如我的表是这样的:
ID Banana_count
1 13
2 23
3 56
原始计数来自其他表的连接和查询。
create FRUIT_TABLE as
select id, count (fruit)
from my_table a
where exists (select null from DATE_FED b
where a.id = b.id
and date = (2/11/17)
and fruit_type = 'banana')
group by id;
我的问题是,如何向这个特定的表添加其他属性,使其看起来像:
ID Banana_count Apple_count Orange_count
1 13 35 22
2 23 44
3 56
4 33 55
5 11
我将不得不向 FRUIT_TABLE 添加更多可能不在当前表中的 ID,但对于当前与 ID 关联的水果,我想将它们添加到同一行。
最佳答案
这是 merge
的经典用例:
merge into fruit_table
using apple_table
on (fruit_table.id = apple_table.id)
when matched then update set
fruit_table.apples = apple_table.apples
when not matched then insert (id,apples)
values(
apple_table.id,
apple_table.apples
);
我稍微简化了这个问题,这样您就可以从一个只有 id 和苹果数量的表中插入数据,这样合并的结构就更加清晰了。但是您可以在语句的 using...
部分插入一个子查询来满足您的实际需求。
关于sql - 如何在 id 字段上可能有匹配项的地方添加一个新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43940943/