sql—mysql中的季度对季度/月对月分析

frebpwbc  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(486)

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

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

同样,也可以每月进行一次分析
我也不反对用不同的格式存储数据。。。可以在不同的字段中拆分日期,如月份季度年份
我在苦苦挣扎

9bfwbjaz

9bfwbjaz1#

可以使用条件聚合:

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) ;
fxnxkyjh

fxnxkyjh2#

试试这个:

SELECT YEAR(disbursementdate) as _year, quarter, SUM(amount)
    FROM
       (
      SELECT disbursementdate, QUARTER(disbursementdate) as quarter, 
       amount,  product, cluster
       FROM mytable
   ) AS sub_query
  GROUP BY _year, quarter

格式有点不同,但应该更好的分析

相关问题