2011-05-06 50 views
1

我有一個行列表,並且我想在分組(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 :)

回答

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計數:(也有用的,如果需要其他countings)

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 
+0

+1:打我吧 – 2011-05-06 22:15:34

+0

初學者的運氣! – Ryan 2011-05-06 22:16:23

+0

謝謝你的試用!但不是,我需要一種'SELECT標題,SUM(這裏)從...' – kwichz 2011-05-06 22:18:56