SQL:计算值的出现次数

ech*_*cho 4 sql group-by count

user | fruit
------------
1    | apple
1    | apple
1    | apple
2    | apple
2    | apple
1    | pear
Run Code Online (Sandbox Code Playgroud)

试图结合countgroup by得到

user | apples | pears
---------------------
1    | 3      | 1
2    | 2      | 0
Run Code Online (Sandbox Code Playgroud)

任何有关如何进行的提示都表示赞赏.

jar*_*rlh 6

使用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
Run Code Online (Sandbox Code Playgroud)