2013-06-12 172 views
1

我想計算group by子句中使用的每個不同的組。我使用這個查詢現在:MySQL按分組計數多列

SELECT language, group, count(*) AS frequency 
FROM bfs 
where firstname <> '' 
GROUP BY language, group 

這使我產生這樣的:

'Language' 'Group'    'Frequency' 
'ARABIC' 'LEBANESE'    1080 
'ARABIC' 'MUSLIM'    40963 
'ARABIC' 'MUSLIM MIDDLE EAST'  349 
'ARABIC' 'MUSLIM NORTH AFRICAN' 549 

我想是:不是語言和組列的每個組合的總頻率,我想知道每種語言和組屬性的多條記錄是如何有

'Language' 'Group' 'Frequency' 'Language Frequency' 'Group Frequency' 
'ARABIC' 'LEBANESE' 1080  42941    1080 

其中語言的頻率代表了「阿拉伯語」作爲其值的行總數;類似的組頻率表示包含'LEBANESE'作爲組頻率的總行數。 任何幫助將不勝感激。

謝謝!

+0

是性能和簡易此查詢更重要? –

回答

3
SELECT 
    g.language, g.`group`, g.frequency, 
    gl.language_frequency, gg.group_frequency 
FROM 
     (SELECT language, `group`, COUNT(*) AS frequency 
     FROM bfs 
     WHERE firstname > '' 
     GROUP BY language, `group` 
    ) AS g 
    JOIN 
     (SELECT language, COUNT(*) AS languageFrequency 
     FROM bfs 
     WHERE firstname > '' 
     GROUP BY language 
    ) AS gl 
     ON gl.language = g.language 
    JOIN 
     (SELECT `group`, COUNT(*) AS group_frequency 
     FROM bfs 
     WHERE firstname > '' 
     GROUP BY `group` 
    ) AS gg 
     ON gg.`group`= g.`group` ; 
+0

太棒了!非常感謝。它給了我我正在尋找的東西。謝謝你的幫助。 – Namaloom