按年份(col)和月份(行)读取数据

时间:2017-12-21 11:47:10

标签: mysql sql

我真的需要你的mysql查询帮助,我没有得到任何线索。

假设我有一个包含两列的表:

entryDate - datetime
Recruits - int

我正在尝试构建一个mysql查询来获取像图像一样的输出。请分享查询。

Sample Output Data

1 个答案:

答案 0 :(得分:0)

您可以使用条件聚合和算术执行此操作:

select monthname(entryDate) as mon,
       sum(case when year(entryDate) = 2016 then recruits else 0 end) as recruits_2016,
       sum(case when year(entryDate) = 2017 then recruits else 0 end) as recruits_2017,
       (sum(case when year(entryDate) = 2017 then recruits end) /
        sum(case when year(entryDate) = 2017 then recruits end) 
       ) - 1 as change
from t
where entryDate between '2016-01-01' and entryDate < '2018-01-01'
group by monthname(entryDate)
order by min(entryDate);