sql - 如何在 id 字段上可能有匹配项的地方添加一个新列

标签 sql database oracle

我目前有一个表,其中包含一个 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/

相关文章:

mysql - 计算具体值。 mysql

sql - 如何在包含最大值的表中查找记录?

sql - 减少 T-SQL 查询的运行时间

ruby-on-rails - “拆分”ActiveRecord 集合

oracle - int 值,只有正项

mysql - 在提供额外选择的同时对查询进行分组

mysql - 我通过某种条件选择所有列,我只想选择其中包含一些数据的那些列

Android - SD 卡上的 SQLite 数据库

php - 如何选择更多条件的用户

java - 设置 WebLogic Server 11g (10.3.6) : Native Library to read the password securely from commandline is not found 时出错