结合group by和count mysql

时间:2017-07-12 12:22:23

标签: mysql

我需要使用group by来找出表中的所有状态:

SELECT status FROM table GROUP BY status

然后计算找到的结果

SELECT count(id) WHERE status = [STATUS]

所以表格如下:

+--------------------+
| ID | STATUS | NAME |
+--------------------+
|0001| BOUGHT | JOHN | 
----------------------
|0002| BOUGHT | JOHN | 
----------------------
|0003| CANCEL | JOHN | 
----------------------
|0004| BOUGHT | JOHN | 
----------------------
|0005| CANCEL | JOHN | 
---------------------
|0006| BOUGHT | JOHN | 
----------------------
|0007| BOUGHT | JOHN | 
----------------------
|0008| SAVE   | JOHN | 
----------------------
|0009| SAVE   | JOHN | 
----------------------
|0010| BOUGHT | JOHN | 
----------------------
|0011| SAVE   | JOHN | 
----------------------

会产生如下结果:

STATUS | COUNT
---------------
SAVE   | 3
BOUGHT | 6
CANCEL | 2

感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

使用以下查询:

SELECT status, count(id) as CNT FROM table GROUP BY status

答案 1 :(得分:0)

只按状态分组,这将为您提供所需的结果

select status, count(id) as COUNT FROM table GROUP BY status