參考~
select sex
,sum(case when age between 1 and 19 then 1 else 0 end) as a
,sum(case when age between 20 and 30 then 1 else 0 end) as b
,sum(case when age between 31 and 40 then 1 else 0 end) as c
,sum(case when age between 41 and 50 then 1 else 0 end) as d
,sum(case when age > 50 then 1 else 0 end) as e
from 表格
group by sex
SELECT
`test`.`sex`,
IFNULL((SELECT COUNT(`sex`) FROM `[table_name]` AS `intab` WHERE `intab`.`sex` = `test`.`sex` AND `intab`.`age` BETWEEN 20 AND 30 GROUP BY `intab`.`sex`), 0) AS '20-30',
IFNULL((SELECT COUNT(`sex`) FROM `[table_name]` AS `intab` WHERE `intab`.`sex` = `test`.`sex` AND `intab`.`age` BETWEEN 30 AND 40 GROUP BY `intab`.`sex`), 0) AS '30-40',
IFNULL((SELECT COUNT(`sex`) FROM `[table_name]` AS `intab` WHERE `intab`.`sex` = `test`.`sex` AND `intab`.`age` BETWEEN 40 AND 50 GROUP BY `intab`.`sex`), 0) AS '40-50',
IFNULL((SELECT COUNT(`sex`) FROM `[table_name]` AS `intab` WHERE `intab`.`sex` = `test`.`sex` AND `intab`.`age` > 50 GROUP BY `intab`.`sex`), 0) AS '50以上'
FROM `[table_name]` AS `test` GROUP BY `test`.`sex`