Search code examples
mysqlsqldatabasefinance

Quarter on Quarter/ Month on Month analysis in mysql


I've loans data and I want to compare sales in different years based on quarter or month

My data looks like this

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

So After querying, I'd ideally want the result to look like this

 Quarter | 2017 | 2018
   Q1    | 1000 | 0
   Q2    | 100  | 1000

Similarly, it can be done for a monthly analysis as well

I'm not averse to storing data in a different format either ... can split date in different field like month quarter year

I'm struggling with query


Solution

  • You can use conditional aggregation:

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

    If you wanted year/quarter on separate rows, you would do:

    select year(disbursementdate) as year, quarter(disbursementdate) as quarter,
           sum(amount)
    from 
    group by year(disbursementdate), quarter(disbursementdate) ;