mysql表中的sum值,其中userid是相同的

时间:2015-03-22 19:04:13

标签: mysql

我已经在SO上阅读了不同的答案,但我坚持这个问题。请帮忙。

我有一个名为“activeuser”的mysql视图:

userid  COUNT(*)    ACRONYM
1       23          admin
2       2           doe
3       4           tompa
12      4           Marre
13      1           Mia
1       2           admin
3       1           tompa
12      1           Marre
13      1           Mia
2       1           doe
3       1           tompa
12      1           Marre

如何对COUNT列求和,以便得到以下想要的结果?

userid  COUNT(*)    ACRONYM
1       25          admin
2       3           doe
3       6           tompa
12      6           Marre
13      1           Mia

EDITED: 我使用此查询来创建视图:

CREATE VIEW activeuser AS
(SELECT boats_comments.userid, COUNT(boats_comments.userid), boats_user.acronym, boats_user.email
  FROM boats_comments
  INNER JOIN boats_user
  ON boats_comments.userid = boats_user.id
  GROUP BY boats_comments.userid
  ORDER BY COUNT(boats_comments.userid) DESC)
  UNION ALL
(SELECT boats_answers.userid, COUNT(boats_answers.userid), boats_user.acronym, boats_user.email
  FROM boats_answers
  INNER JOIN boats_user
  ON boats_answers.userid = boats_user.id
  GROUP BY boats_answers.userid
  ORDER BY COUNT(boats_answers.userid) DESC)  
    UNION ALL
  (SELECT boats_questions.userid, COUNT(boats_questions.userid), boats_user.acronym, boats_user.email
  FROM boats_questions
  INNER JOIN boats_user
  ON boats_questions.userid = boats_user.id
  GROUP BY boats_questions.userid
  ORDER BY COUNT(boats_questions.userid) DESC)

我的目标是通过查看评论,问题和答案的数量来查看哪些用户最活跃...但我被卡住了......

2 个答案:

答案 0 :(得分:0)

select userid, count(*) from activeuser group by userid;

答案 1 :(得分:0)

由于您视图中的结果有重复,我猜视图的基础代码是对可能不应该分组的内容进行分组。

您可以通过对其应用SUM来获得所需的结果:

select userid, sum("whatever column2 is named") as "Count", Acronym 
from activeuser group by userid, Acronym;