简体   繁体   English

如何计算MySQL中不同项目的项目数?

[英]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个...)

You simply need to group your table, applying a suitable aggregate function: 您只需要对表进行分组 ,并应用合适的聚合函数:

SELECT   status, COUNT(*)
FROM     my_table
GROUP BY status

See it on sqlfiddle . sqlfiddle上看到它。

If a status is missing, you can treat it as 0 from within your application code. 如果缺少状态,则可以在应用程序代码中将其视为0。

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不是其中之一。

Example SQLFiddle 示例SQLFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM