我有一个表名“ demo”,其字段为id(PK),用户和具有以下数据的项目:
id user item
== ==== =====
1 anuj A
2 anuj A
3 anuj A
4 anuj B
5 anuj B
6 anuj B
7 patil A
8 patil A
9 patil A
10 rahul B
11 rahul B
12 tanmay A
13 tanmay A
现在,我想编写一个查询,该查询将给我这样的结果:
User Count of A Count of B
==== ========== ===========
anuj 3 3
patil 3 0
rahul 0 2
tanmay 2 0
基本上有可能吗?我尝试过但未成功。
最佳答案
使用Conditional Aggregate
Case statement
聚合内的count
将产生1
或NULL
。由于NULL
值已由聚合函数消除,因此该计数将仅在满足条件时才考虑对该值进行计数
select User,
Count(case when item = 'A' then 1 end) as `Count of A`,
Count(case when item = 'B' then 1 end) as `Count of B`
From yourtable
Group by User
关于mysql - 如何编写将对一个表的同一列中的两种类型的值进行计数的SQL查询?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32168157/