2011-07-28 102 views
0

我試過尋找這個,但是找不到類似的東西。大多數問題都是關於通過語句在組中使用條件。MySQL - 如何GROUP BY有條件的列

我有一個表'列'主題'和'內容'。我想統計'內容'中銀行名稱的實例。

如果我做了以下工作,我可以得到我期望的結果:每行記錄有一行,有些是「BofA」,有些是「USAA」,大部分是「Other」。

select 
case 
    when content like '%bank of america%' then "BofA" 
    when content like '%usaa%' then "USAA" 
    else "Other" 
end as 'FI' 
from topics 

結果是一樣的東西:

FI 
Other 
Other 
BofA 
Other 
Other 
USAA 
Other 
... 

好,很好。但是,如果我試圖通過FI做計數()和組:

select 
case 
    when content like '%bank of america%' then "BofA" 
    when content like '%usaa%' then "USAA" 
    else "Other" 
end as 'FI', 
count(*) 

from topics 

group by 'FI' 

結果:

FI  | count(*) 
Other | 43203 

我想是這樣的:

FI  | count(*) 
BofA | 1298 
USAA | 701 
Other | 41134 

我不能弄清楚我做錯了什麼。我知道我可以通過幾種不同的方式做到這一點,但似乎應該這樣做......我也接受其他方法。任何幫助表示讚賞。

回答

0

看起來應該可以工作。但是,你可以試試這個:

select fi,count(*) from 
(
    select 
    case 
    when content like '%bank of america%' then "BofA" 
    when content like '%usaa%' then "USAA" 
    else "Other" 
    end as fi 
    from topics 
) 
group by fi 
+0

你不需要一個表別名嗎?即...從主題)** x **羣由fi – Bohemian

+0

謝謝,那確實工作。儘管我必須給表格一個別名。 –

+0

如果有人知道,我仍然有興趣知道爲什麼原稿不起作用。 –