在GroupBy中选择

时间:2016-01-12 10:28:09

标签: mysql sql

我有以下查询

select YEAR(t1.date) as 'year'
, MONTHNAME(t1.date) as 'month'
, COUNT(*) as total
, if (t1.Sex = 1, 'male','female') as sex
from outpatients t1
where YEAR(t1.date) = 2015 
group by MONTH(t1.date), t1.Sex
order by t1.date, t1.Sex

所以输出看起来像这样:

enter image description here

我想写一个查询,将女性和男性视为列。 所以输出看起来像。

enter image description here

我找不到分组数据的方法

1 个答案:

答案 0 :(得分:2)

您可以使用SUM函数对男性和女性进行求和

select YEAR(t1.date) as year, MONTHNAME(t1.date) as month, COUNT(*) as total
, SUM(CASE WHEN sex = 'male' THEN 1 ELSE 0 END) AS male
, SUM(CASE WHEN sex = 'female' THEN 1 ELSE 0 END) AS female
from outpatients t1
where YEAR(t1.date) = 2015 
group by MONTH(t1.date), t1.Sex
order by t1.date, t1.Sex