【问题标题】:SQL count productsSQL 计数产品
【发布时间】:2021-01-24 08:06:48
【问题描述】:

我有桌子:

name    product
john     beer
john     milk
john     tea
john     beer
emily    milk
emily    milk
emily    tea
john     beer

我需要从这个表中选择,当输出是:

name count(tea)  count(beer) count(milk)  count(total)
john    1             3          1              5
emily   1             0          2              3

知道怎么做吗?

数据库:甲骨文 12

【问题讨论】:

  • 如果有人突然插入(哑光、咖啡),预期的结果是什么?
  • 您使用的是哪个 dbms?

标签: sql oracle count pivot oracle12c


【解决方案1】:

使用条件聚合:

select name
    sum(case when product = 'tea' then 1 else 0 end) cnt_tea,
    sum(case when product = 'beer' then 1 else 0 end) cnt_beer,
    sum(case when product = 'milk' then 1 else 0 end) cnt_milk,
    count(*) total
from mytable
group by name

根据您的数据库,可能有更简洁的选项可用于表达条件计数。

【讨论】:

  • 感谢您的快速回复。你帮了我很多。
猜你喜欢
  • 2013-11-22
  • 1970-01-01
  • 2018-04-24
  • 1970-01-01
  • 2018-12-29
  • 2021-08-24
  • 1970-01-01
  • 2011-11-27
  • 1970-01-01
相关资源
最近更新 更多