分组时如何根据条件求和
我有一个行列表,我想在分组时对行数进行求和(一种 COUNT),但仅当每行字段 customField=0 时才进行求和。
示例:
title customField
aaa 1
aaa 0
bbb 0
ccc 1
bbb 1
aaa 0
那么,输出应该是:
aaa 2
bbb 1
ccc 0
How can I do it with 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
只有当 forum_messages.original=0
时,我才必须计算 COUNT(forum_messages.id) AS Total_replies
>,这就是我请求 SUM 的原因:)
I have a list of rows, and I'd like to SUM the number of the lines when grouping (a sort of COUNT) but only when, for each row, the field customField=0.
Example :
title customField
aaa 1
aaa 0
bbb 0
ccc 1
bbb 1
aaa 0
So, the output should be :
aaa 2
bbb 1
ccc 0
How can I do it with MySql?
EDIT
In fact my real Query is this one :
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
And I have to count COUNT(forum_messages.id) AS total_replies
only when forum_messages.original=0
, that's why I request the SUM :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需过滤结果集以排除
customField=1
,即结果:
显示所有标题,包括那些计数为 0 的标题:(如果需要其他计数也很有帮助)
结果:
更紧凑(但有效)仅在 MYSQL 中):
Just filter the result set to exclude
customField=1
, i.e.Result:
To show all titles, including those which have a 0 count: (also helpful if other countings are needed)
Result:
More compact (but works only in MYSQL):