Mysql计数按组发生

时间:2013-01-23 09:32:23

标签: mysql sql select

您好我在mysql DB上有下表。

╔═══════════╦═════════╦════════╦════════════════╗
║ REVIEW_ID ║ USER_ID ║ STATUS ║   DATE_ADDED   ║
╠═══════════╬═════════╬════════╬════════════════╣
║       218 ║       2 ║ cool   ║ 20130121134811 ║
║       218 ║       2 ║ cool   ║ 20130121134812 ║
║       218 ║       2 ║ lame   ║ 20130121134813 ║
║       218 ║       2 ║ funny  ║ 20130121134814 ║
║       218 ║       2 ║ funny  ║ 20130121134815 ║
║       218 ║       2 ║ funny  ║ 20130121134816 ║
║       218 ║       2 ║ lame   ║ 20130121134817 ║
╚═══════════╩═════════╩════════╩════════════════╝

我怎样才能得到一个结果,当我根据user_id进行查询时,我需要得到每种类型的总状态结果:

╔════════╦════════════╗
║ STATUS ║ TOTALCOUNT ║
╠════════╬════════════╣
║ cool   ║          2 ║
║ funny  ║          3 ║
║ lame   ║          2 ║
╚════════╩════════════╝

由于

4 个答案:

答案 0 :(得分:12)

使用COUNT()聚合函数,并根据status

对它们进行分组
SELECT  status, COUNT(*) totalCount
FROM    tableName
GROUP   BY status

OTHER(S)

答案 1 :(得分:1)

SELECT status, count(*)
FROM your_table
GROUP BY status

答案 2 :(得分:1)

SELECT status, count(*)
FROM yourtable
GROUP BY status
;

答案 3 :(得分:0)

SELECT  STATUS, COUNT(*) AS TOTALCOUNT
FROM    tableName
GROUP   BY STATUS
HAVING   USER_ID = user_id you need