SQL-基于过滤器的聚合列

时间:2020-03-10 12:15:40

标签: sql sql-server select sum

我的数据具有ID,日期和points_earned字段。每行代表该日期该ID赢得的积分。

我想创建与此类似的东西:

ID | Points_Earned_January | Points_Earned_February | Points_Earned_March

结果应为GROUP BY ID。 Points_Earned_January应该给出该ID在1月份所赚取的所有points中的SUM

我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以使用条件聚合:

select id,
       (case when date >= '2020-02-01' and date < '2020-03-01' then points else 0 end) as points_feb,
       (case when date >= '2020-03-01' and date < '2020-04-01' then points else 0 end) as points_mar
from t
group by id;