分组时如何与条件求和

时间:2011-05-06 22:11:05

标签: mysql sql aggregate-functions

我有一个行列表,我想在分组(一种COUNT)时对行数进行求和,但只有当每行有 customField = 0 时才行

示例:

title       customField
aaa         1
aaa         0
bbb         0
ccc         1
bbb         1
aaa         0

所以,输出应该是:

aaa 2
bbb 1
ccc 0

如何使用MySql进行操作?

修改

实际上我真正的查询就是这个:

SELECT forum_categories.title, COUNT(forum_topics.id) AS total_topics, COUNT(forum_messages.id) AS total_replies, MAX(forum_messages.date) AS last_message
FROM forum_categories
JOIN forum_topics ON forum_topics.category_id = forum_categories.id 
JOIN forum_messages ON forum_messages.topic_id = forum_topics.id
GROUP BY forum_categories.id ORDER BY forum_categories.date

我必须在COUNT(forum_messages.id) AS total_replies时计算forum_messages.original=0,这就是我要求SUM的原因:)

1 个答案:

答案 0 :(得分:7)

只需过滤结果集即可排除customField=1,即

  SELECT title, COUNT(*) AS numTitle
    FROM yourtable
   WHERE customField = 0
GROUP BY title
ORDER BY numTitle DESC

结果:

aaa 2
bbb 1

显示所有标题,包括那些具有0计数的标题:(如果需要其他计数也很有帮助)

  SELECT title
       , SUM(CASE WHEN customField=0 THEN 1 ELSE 0 END) AS numTitle
    FROM yourtable
GROUP BY title
ORDER BY numTitle DESC

结果:

aaa 2
bbb 1
ccc 0

更紧凑(但仅适用于MYSQL):

  SELECT title
       , SUM(customField=0) AS numTitle
    FROM yourtable
GROUP BY title
ORDER BY numTitle DESC