MySQL:基于年份值的动态视图

时间:2018-01-12 11:07:54

标签: mysql sql

以下是我的输入表:

输入表格

|---------------------|------------------|
|      date           |        total     |
|---------------------|------------------|
|    12-1-2017        |         10       |
|---------------------|------------------|
|    12-2-2017        |         20       |
|---------------------|------------------|
|    12-1-2016        |         30       |
|---------------------|------------------|
|    12-2-2016        |         40       |
|---------------------|------------------|
|    12-3-2016        |         50       |
|---------------------|------------------|

我希望查询的结果具有如下的动态年份列:

|---------------------|------------------|------------------|
|        day          |   total_2017     |   total_2016     |
|---------------------|------------------|------------------|
|       12-1          |         10       |         30       |
|---------------------|------------------|------------------|
|       12-2          |         20       |         40       |
|---------------------|------------------|------------------|
|       12-3          |         0        |         50       |
|---------------------|------------------|------------------|

有人能用最好的方法帮助我吗?

1 个答案:

答案 0 :(得分:1)

这是一种方法:

select month(date), day(date),
       sum(case when year(date) = 2017 then total else 0 end) as total_2017,
       sum(case when year(date) = 2016 then total else 0 end) as total_2016
from t
group by month(date), day(date);
相关问题