[英]SQL: count occurrences of values
Let 让
user | fruit
------------
1 | apple
1 | apple
1 | apple
2 | apple
2 | apple
1 | pear
Trying to combine count
and group by
to get 尝试将
count
和group by
结合起来
user | apples | pears
---------------------
1 | 3 | 1
2 | 2 | 0
Any hints on how to proceed are appreciated. 任何有关如何进行的提示都表示赞赏。
Use case
expressions to do conditional counting: 用
case
表达式进行条件计数:
select user,
count(case when fruit = 'apple' then 1 end) as apples,
count(case when fruit = 'pear' then 1 end) as pears
from tablename
group by user
If you´re working on an Oracle, you would use the PIVOT-function: 如果您正在使用Oracle,则可以使用PIVOT函数:
SELECT *
FROM fruit t
PIVOT (COUNT(fruit) AS cnt
FOR(fruit) IN ('apple' AS apple
, 'pear' AS pear) );
More details and full samples on PIVOT / UNPIVOT you´ll find in the web (fe here https://oracle-base.com/articles/11g/pivot-and-unpivot-operators-11gr1 ) 有关PIVOT / UNPIVOT的更多详细信息和完整示例,请访问网站(例如https://oracle-base.com/articles/11g/pivot-and-unpivot-operators-11gr1 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.