avg sale of quarter with previous quarter avg sale

前端 未结 3 2012
北荒
北荒 2021-01-16 08:09

I have a table one in which there are various attribute like region product,year,qtr,month,sale. I have to calculate the avg_qtr sale of each product having same region and

3条回答
  •  心在旅途
    2021-01-16 08:50

    You need to join on some sub-select statements that will get the previous quarter avg. You will also need to do a union of two statements because for quarters 2,3,4 you can simply subtract a quarter on the join statement to the previous qtr avg, but when it is the 1st quarter you need to subtract a year and set the previous qtr = 4. This statement should work for what you have described.

    --handles when the current quarter being viewed is 2,3,or 4 because those would still be in the same year when looking at the previous quarter
    select  t1.product,
            t1.year,
            t1.month,
            t1.sales ,
            t1.qtr,
            round(avg(t1.sales) over (partition by t1.qtr,t1.year),2) as av,
            t2.prev_av
    from one t1
    left join ( select
                    product,
                    year,
                    month,
                    sales ,
                    qtr,
                    round(avg(sales) over (partition by qtr,year),2) as prev_av
                from one
                ) t2
    on t1.year = t2.year
    and (t1.qtr - 1) = t2.qtr
    where t1.qtr in (2,3,4)
    union
    --handles the 1st quarter of the year when you need to grab the 4th quarter of the previous year for the previous avg
    select  t3.product,
            t3.year,
            t3.month,
            t3.sales ,
            t3.qtr,
            round(avg(t3.sales) over (partition by t3.qtr,t3.year),2) as av,
            t4.prev_av
    from one t3
    left join ( select
                    product,
                    year,
                    month,
                    sales,
                    qtr,
                    round(avg(sales) over (partition by qtr,year),2) as prev_av
                from one
                ) t4
    on (t3.year - 1) = t4.year
    and t4.qtr = 4
    where t3.qtr = 1;
    

提交回复
热议问题