在mysql中按月分析季度/月份

时间:2018-06-04 09:29:48

标签: mysql sql database finance

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

我的数据看起来像这样

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

同样,它也可以进行月度分析

我不反对以不同的格式存储数据......可以将日期分成不同的字段,如月份季度

我正在努力解决查询问题

2 个答案:

答案 0 :(得分:2)

您可以使用条件聚合:

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

答案 1 :(得分:1)

试试这个:

    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

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