我有这张桌子:
ID CODE WEEK SEX
1 abc 1 F
2 abc 2 M
3 xyz 3 F
4 abc 1 M
我正在使用此查询来过滤数据:
SELECT `code`,`week`,`sex`, COUNT(`week`) as cnt
FROM `table`
WHERE `code` = "abc"
and `sex` = "F"
group by `week`
having (`week` > 0)
UNION ALL
SELECT `code`,`week`,`sex`, COUNT(`week`) as cnt
FROM `table`
WHERE `code` = "abc"
and `sex` = "M"
group by `week`
having (`week` > 0)
这就是结果:
CODE WEEK SEX cnt
abc 1 F 1
abc 1 M 1
abc 2 M 1
但现在我需要以这种方式显示数据:
CODE WEEK M F
abc 1 1 1
abc 2 1 0
所以我有这个问题:
SELECT
`WEEK`,`CODE`,
GROUP_CONCAT(if(`SEX` = "F", `cnt`, NULL)) AS "F",
GROUP_CONCAT(if(`SEX` = "M", `cnt`, NULL)) AS "M"
FROM `temp_table`
GROUP BY `WEEK`
ORDER BY CAST(`WEEK` AS UNSIGNED)
如何合并这2个查询?有一个更好的方法吗?
答案 0 :(得分:2)
SELECT `WEEK`,`CODE`
, SUM(IF(`SEX` = "F", cnt, 0)) AS `F`
, SUM(IF(`SEX` = "M", cnt, 0)) AS `M`
FROM `table`
GROUP BY `WEEK`,`CODE`
;
我不确定你为什么要做那个奇怪的ORDER BY,我很确定你也想要在CODE上分组。 (编辑:是的,CAST适用于周数据类型。)
如果使用第一个查询作为“来源”,请参阅以下内容:
SELECT `WEEK`,`CODE`
, SUM(IF(`SEX` = "F", 1, 0)) AS `F`
, SUM(IF(`SEX` = "M", 1, 0)) AS `M`
FROM ([original query goes in here]) `subQ`
GROUP BY `WEEK`,`CODE`
;