我有一个表存储购买日期和价格。
例如
date | price
---------------------
2014-1-12 | 6.50
2014-2-34 | 10.99
2015-1-01 | 3.22
2015-2-14 | 4.12
Run Code Online (Sandbox Code Playgroud)
等等。
我想要实现的目标:输出一年中每月分组的购买总和的查询。
但重要的是,我需要在列中包含不同的年份,以便能够为每年制作一个带有单独线条的图表。所以我需要的输出是这样的:
MONTH | 2014 | 2015
JAN | 123.23 | 99.1
FEB | 457.00 | 122.00
MAR | 299.99 | 789.12
... |
NOV | 333.33 | 10.99
DEC | 100.00 | 20.10
Run Code Online (Sandbox Code Playgroud)
这可能吗?我搜索了很长一段时间,例如“逐年”查询等,但我找不到任何东西。
任何帮助是极大的赞赏!
只需使用条件聚合:
select monthname(date) as mon,
sum(case when year(date) = 2014 then price else 0 end) as price_2014,
sum(case when year(date) = 2015 then price else 0 end) as price_2015
from table t
group by monthname(date)
order by max(month(date));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2016 次 |
| 最近记录: |