mysql计数group_concat中的项目

时间:2015-12-20 07:08:39

标签: mysql sql select group-concat

我在MySQL中使用GROUP_CONCAT时遇到了麻烦 我的表g0如下:

ID  Age Sex
-------------
1   16  Male
2   18  Female
3   16  Male
4   18  Female
5   16  Male

但我需要表格看起来像

ID        count
1,3,5       3
2,4         2

我尝试了这个查询:

SELECT GROUP_CONCAT(
CONCAT(cnt)) cnts FROM 
(SELECT COUNT(ID) as cnt FROM g0  GROUP BY Age , Sex order by ID Desc) ;

但我收到此错误消息:

1248. Every derived table must have it's own alias

1 个答案:

答案 0 :(得分:4)

count内无需group_concat - 只需将其选为具有相同group by表达式的其他项:

SELECT   GROUP_CONCAT(id), COUNT(*)
FROM     g0
GROUP BY age, sex
ORDER BY 1 DESC