我想计算group by子句中使用的每个不同的组。我现在正在使用此查询:
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
其中语言频率表示以'ARABIC'作为其值的总行数;类似地,组频率表示包含“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` ;