I have this table:
ID CODE WEEK SEX
1 abc 1 F
2 abc 2 M
3 xyz 3 F
4 abc 1 M
and I am using this query to filter the data:
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)
and this is the result:
CODE WEEK SEX cnt
abc 1 F 1
abc 1 M 1
abc 2 M 1
But now I need to show the data in this way:
CODE WEEK M F
abc 1 1 1
abc 2 1 0
So I have this query:
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)
How can I combine this 2 queries? Is there a better way to do this?
weekandsex.