如何在几个月(1月,2月,3月等)对日期进行分组

时间:2018-04-25 14:34:00

标签: sql sql-server

嗨我有这样一张桌子


+-------+------------+----------+---------+
| name  | date       | quantity | price   |
+-------+------------+----------+---------+
| art1  | 2017-01-05 | 10       | 5543.32 |
+-------+------------+----------+---------+
| art2  | 2017-01-15 | 16       | 12.56   |
+-------+------------+----------+---------+
| art3  | 2017-02-08 | 5        | 853.65  |
+-------+------------+----------+---------+
| art4  | 2017-03-06 | 32       | 98.65   |
+-------+------------+----------+---------+

我想展示这些信息


+-------+------------+----------+---------+
| name  | January    | February | March   |
+-------+------------+----------+---------+
| art1  | 5543.32    | 0        | 0       |
+-------+------------+----------+---------+
| art2  | 12.56      | 0        | 0       |
+-------+------------+----------+---------+
| art3  | 0          | 853.65   | 0       |
+-------+------------+----------+---------+
| art4  | 0          | 0        | 98.65   |
+-------+------------+----------+---------+

我该怎么做?我在sql中有点生疏。 感谢

1 个答案:

答案 0 :(得分:1)

我会使用条件聚合:

select name,
       sum(case when date >= '2017-01-01' and date < '2017-02-01' then price else 0 end) as january,
       sum(case when date >= '2017-02-01' and date < '2017-03-01' then price else 0 end) as february,
       sum(case when date >= '2017-03-01' and date < '2017-04-01' then price else 0 end) as march
from t
group by name;