Interview question:How to get last 3 month aggregation at column level?

前端 未结 3 1046
执笔经年
执笔经年 2021-01-16 11:39

This is the question i was being asked at Apple onsite interview and it blew my mind. Data is like this:

orderdate,unit_of_phone_sale

20190806,3000

2019070         


        
3条回答
  •  孤独总比滥情好
    2021-01-16 12:23

    I think LEAD function can help here -

    SELECT TO_CHAR(orderdate, 'YYYYMM') "DATE"
      ,unit_of_phone_sale M_1_Sale
      ,LEAD(unit_of_phone_sale,1,0) OVER(ORDER BY TO_CHAR(orderdate, 'YYYYMM') DESC) M_2_Sale
      ,LEAD(unit_of_phone_sale,2,0) OVER(ORDER BY TO_CHAR(orderdate, 'YYYYMM') DESC) M_3_Sale
      ,LEAD(unit_of_phone_sale,3,0) OVER(ORDER BY TO_CHAR(orderdate, 'YYYYMM') DESC) M_4_Sale
    FROM table_sales
    

    Here is the DB Fiddle

提交回复
热议问题