对多个列进行计数和分组

时间:2015-04-20 10:02:48

标签: mysql sql

我有来自当前查询的数据

Status Name
1      Lester Boyer
2      Lester Boyer
4      Lester Boyer
1      Lester Boyer
2      Lester Boyer
0      Lester Boyer
3      Lester Boyer
1      Lester Boyer
1      Rosalinda Marks
2      Rosalinda Marks

但我想计算针对该用户的状态数,因此最终表应该看起来像

Status Name            Count
0      Lester Boyer    1
1      Lester Boyer    3
2      Lester Boyer    2
3      Lester Boyer    1
4      Lester Boyer    1
1      Rosalinda Marks 1
2      Rosalinda Marks 1

当前查询

SELECT allocation.status, CONCAT(profile.forename, ' ', profile.surname) AS name
FROM allocation
  INNER JOIN user ON allocation.user_id = user.id
  INNER JOIN profile ON user.id = profile.user_id

2 个答案:

答案 0 :(得分:3)

您的查询中似乎不需要user表。您的版本只需group by

SELECT a.status, CONCAT(p.forename, ' ', p.surname) AS name, COUNT(*)
FROM allocation a INNER JOIN 
     profile
     ON p.user_id = a.user_id
GROUP BY a.status, CONCAT(p.forename, ' ', p.surname) ;

答案 1 :(得分:0)

SELECT allocation.status, CONCAT(profile.forename, ' ', profile.surname) AS name, COUNT(allocation.status) AS Count
FROM allocation
  INNER JOIN user ON allocation.user_id = user.id
  INNER JOIN profile ON user.id = profile.user_id
GROUP BY CONCAT(profile.forename, ' ', profile.surname),
         allocation.status
ORDER BY name, allocation.status