Transpose/Pivot Rows to Columns and Sum

后端 未结 1 1886
春和景丽
春和景丽 2021-01-22 02:27

Here is my query

SELECT * 
FROM requirementRange

PeakRange,DaysOfReq columns are nvarchar datatype and Total

相关标签:
1条回答
  • 2021-01-22 03:15

    You should be able to use something similar to the following:

    select 
      peakrange,
      coalesce([Day 0], 0) [Day 0], 
      coalesce([Day 1], 0) [Day 1], 
      coalesce([Day 2], 0) [Day 2],
      coalesce([>2 Days], 0) [>2 Days],
      peak_Total
    from
    (
      select peakrange, daysofreq, total,
        sum(total) over(partition by PeakRange) peak_Total
      from requirementRange
    ) d
    pivot
    (
      sum(total)
      for daysofreq in ([Day 0], [Day 1], [Day 2],
                        [>2 Days])
    ) piv
    order by peakrange;
    

    See SQL Fiddle with Demo

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