How to group by the each week upto last six week sundays dates in sql?

后端 未结 1 1775
既然无缘
既然无缘 2020-12-22 14:59

Currently am working on the report. What i need is sample table,

Instance Type   Sep-23  Sep-16  Sep-09  Sep-02  Aug-26  Aug-19
-----------------------------         


        
相关标签:
1条回答
  • 2020-12-22 15:35

    I made a few assumptions about the data that you posted.

    First, the values you posted all state the year as 2011 but the final end dates as column headers do not correspond to 2011, they are the Sunday values for 2012 so I altered the data. Also the final entry of Early ASN 8/15/2011 12:00, I believe is supposed to be a Late ASN entry otherwise the totals to do match up.

    To get the results, you want you will want to apply the PIVOT function. This function allows you to aggregate the values and then convert them to columns.

    SET DATEFIRST 1 -- set this so the start of the week is Sunday
    select InstanceType,
      sum([39]) as Sep_23, 
      sum([38]) as Sep_16, 
      sum([37]) as Sep_09, 
      sum([36]) as Sep_02, 
      sum([35]) as Aug_26, 
      sum([34]) as Aug_19
    from
    (
      select SPGI01_INSTANCE_TYPE_C as InstanceType,
        [39], [38], [37], [36], [35], [34]
      from
      (
        select SPGI01_INSTANCE_TYPE_C,
          DatePart(wk, SPGI01_CREATE_S) WeekNo,
          DATEADD(DAY, 7 -DATEPART(WEEKDAY,SPGI01_CREATE_S),SPGI01_CREATE_S) WeekEnd
        from table1
      ) x
      pivot
      (
        count(WeekEnd)
        for weekno in ([39], [38], [37], [36], [35], [34])
      ) p
    ) x1
    group by InstanceType with rollup
    

    See SQL Fiddle with Demo

    0 讨论(0)
提交回复
热议问题