[英]How to count how many items for distinct items in mysql?
Imagine a have a table with a column named status: 假设有一个表,其中有一个名为status的列:
status
------
A
A
A
B
C
C
D
D
D
How can I count how many rows have A, how many rows have B etc? 如何计算有A的行,有B的行等? this kind of output:
这种输出:
A |B |C |D |E
------------------
3 |1 |2 |3 |0
As for E = O , this will always be A,B,C,D and E Output should be one row (thus 1 query). 对于E = O,它将始终为A,B,C,D,并且E输出应为一行(因此查询1条)。
When doing a distinct count (most returning answer on my searches, it does return how many different elements there are, 4 in this case...) 当进行不重复计数时(我的搜索中最返回的答案,它的确返回了多少个不同的元素,在这种情况下为4个...)
Putting the results into one row is a bit more clumsy that group by: 将结果放在一行中比较笨拙:
Select
sum(status = 'A') 'A',
sum(status = 'B') 'B',
sum(status = 'C') 'C',
sum(status = 'D') 'D',
sum(status = 'E') 'E'
From
my_table
Some databases support pivot
which makes this a bit better. 一些数据库支持
pivot
,这使其变得更好。 MySQL isn't one of them. MySQL不是其中之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.