SQL计数产品
我有一张桌子:SQL计数产品,sql,oracle,count,pivot,oracle12c,Sql,Oracle,Count,Pivot,Oracle12c,我有一张桌子: 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
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
你知道怎么做吗
DB:oracle 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
根据您的数据库,可能有更简洁的选项来表示条件计数。使用条件聚合:
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
根据您的数据库,可能有更简洁的选项来表示条件计数。如果有人突然插入(matt,coffee),预期结果是什么?您使用的是哪种dbms?如果有人突然插入(matt,coffee),预期结果是什么?您使用的是哪种dbms?感谢您的快速回复。你帮了我很多。谢谢你的快速回复。你帮了我很多。