这是我的查询
SELECT * FROM requirementRange
PeakRange,DaysOfReq列为nvarchar数据类型,Total为INT数据类型
PeakRange
DaysOfReq
Total
表格如下
PeakRange DaysOfReq总计 1-3.99> 2天2 9.01+第2天3 1-3.99天0 1 4-5.99天0 1 6-8.99第2天2 9天0 1 9.01+天0 1
预期结果
PeakRange Day 0 Day 1 Day 2> 2天合计 1-3.99 1 0 0 2 3 4-5.99 1 0 0 0 1 6-8.99 0 0 2 0 2 9 1 0 0 0 1 9.01+ 1 0 3 0 4
在这里,我需要将输出从行转换为列,并找到总计并将其放置在每个范围的最后一列中。
您应该可以使用类似于以下内容的东西:
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;