如何在SQL查询中获取分组COUNT的SUM

时间:2014-10-30 15:53:18

标签: mysql sql-server

我正在尝试获得分组计数的总和。

我的表结果是这样的。

ID | Name | count
1     k        5
2     k        4
3     a        12

我希望得到一个结果。

ID | Name | count
 1     k        9
 3     a        12

这是我的真实问题。

SELECT COUNT( clubs_messages.id_user ) AS nbr, users.name, users.id, users.email
FROM users
JOIN clubs_messages ON users.id = clubs_messages.id_user
GROUP BY clubs_messages.id_user
UNION 
SELECT 'SUM' users.name, COUNT( clubs_messages.id_user ) 
FROM users
JOIN clubs_messages ON users.id = clubs_messages.id_user

所以请帮忙。谢谢

2 个答案:

答案 0 :(得分:3)

我认为你只需要GROUP BY Name而不是user_id。请检查以下查询

   SELECT COUNT( clubs_messages.id_user ) AS nbr, users.name
   FROM users
   JOIN clubs_messages ON users.id = clubs_messages.id_user
   GROUP BY users.name

答案 1 :(得分:1)

这里的问题是您按ID而不是按名称进行分组:

SELECT COUNT( clubs_messages.id_user ) AS nbr, users.name, users.id, users.email
FROM users
JOIN clubs_messages ON users.id = clubs_messages.id_user
GROUP BY clubs_messages.id_user

要解决此问题,您需要按名称分组:

SELECT COUNT( clubs_messages.id_user ) AS nbr, users.name, users.id, users.email
FROM users
JOIN clubs_messages ON users.id = clubs_messages.id_user
GROUP BY users.name