SQL 计数产品
SQL count products
我有 table:
name product
john beer
john milk
john tea
john beer
emily milk
emily milk
emily tea
john beer
我需要 select 来自这个 table,输出将是:
name count(tea) count(beer) count(milk) count(total)
john 1 3 1 5
emily 1 0 2 3
知道怎么做吗?
数据库:甲骨文 12
使用条件聚合:
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
根据您的数据库,可能有更简洁的选项可用于表示条件计数。
我有 table:
name product
john beer
john milk
john tea
john beer
emily milk
emily milk
emily tea
john beer
我需要 select 来自这个 table,输出将是:
name count(tea) count(beer) count(milk) count(total)
john 1 3 1 5
emily 1 0 2 3
知道怎么做吗?
数据库:甲骨文 12
使用条件聚合:
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
根据您的数据库,可能有更简洁的选项可用于表示条件计数。