我有贷款数据,我想根据季度或月份比较不同年份的销售额
我的数据是这样的

disbursementdate | amount | product | cluster
2017-01-01       | 1000   | HL      | West
2018-02-01       | 1000   | PL      | East

所以在查询之后,我希望结果是这样的
 Quarter | 2017 | 2018
   Q1    | 1000 | 0
   Q2    | 100  | 1000

同样,它也可以用于每月的分析
我也不反对以不同的格式存储数据…可以在不同的字段中拆分日期,如月/季度/年
我在苦苦思索

最佳答案

可以使用条件聚合:

select quarter(disbursementdate) as quarter,
       sum(case when year(disbursementdate) = 2017 then amount else 0 end) as amount_2017,
       sum(case when year(disbursementdate) = 2018 then amount else 0 end) as amount_2018
from
group by quarter(disbursementdate) ;

如果您想在单独的行上year/quarter,您可以:
select year(disbursementdate) as year, quarter(disbursementdate) as quarter,
       sum(amount)
from
group by year(disbursementdate), quarter(disbursementdate) ;

10-07 20:07