SQL:统计值的出现次数

4

Let

user | fruit
------------
1    | apple
1    | apple
1    | apple
2    | apple
2    | apple
1    | pear

尝试将countgroup by结合起来,以获取
user | apples | pears
---------------------
1    | 3      | 1
2    | 2      | 0

希望能够得到关于如何进行的任何提示。


仅仅使用group by是不够的,你还需要对数据进行透视。 - Mithrandir
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Serg
2个回答

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

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接