我在下面有一个表,它是许多临时表的结果,它涉及join和order by子句。
Type Col1 Col2 Col3 Col4 Col5
Within 30 days 493868 426428 401194 268929 399480
Within 60 days 745 13118 35577 31577 30536
Within 90 days NULL 28222 27312 45085 10432
Within 120 days NULL 12039 13999 38239 11777
Grater than120 days NULL 14806 16531 110783 13091
Blank NULL NULL NULL NULL 29297
Total 494613 494613 494613 494613 494613
我想要输出如下: 当前行值应该是前一行值+当前值..否则直到它与总数匹配为止。
Type Col1 Col2 Col3 Col4 Col5
Within 30 days 493868 426428 401194 268929 399480
Within 60 days 494613 439546 436771 300506 430016
Within 90 days 494613 467768 464083 345591 440448
Within 120 days 494613 479807 478082 383830 452225
Greater than 120 days 494613 494613 494613 494613 465316
Blank 494613 494613 494613 494613 494613
Total 494613 494613 494613 494613 494613
由于我使用了orderby子句,因此我无法使用temptable和派生表。请帮助。我使用了查询:
select e.[type],o.[Col1],h.[Col2],s.[Col3],d.[Col4],e.[Col5]
from #table1 e
left outer join #table2 d on e.[type]=d.[type]
left outer join #table3 s on e.[type]=s.[type]
left outer join #table4 h on e.[type]=h.[type]
left outer join #table5 o on e.[type]=o.[type]
order by case
when e.[type] ='Within 30 days' then 1
when e.[type] ='Within 60 days' then 2
when e.[type] ='Within 90 days' then 3
when e.[type] ='Within 120 days' then 4
when e.[type] ='Greater than 120 days' then 5
when e.[type] ='Blank' then 6
else 7
end
答案 0 :(得分:5)
使用SUM OVER()
窗口聚合函数计算运行总计
Select type,
sum([Count(A)]) Over(order by order_col) as [Count(A)],
sum([Count(B)]) Over(order by order_col) as [Count(B)],
sum([Count(C)]) Over(order by order_col) as [Count(C)],
sum([Count(D)]) Over(order by order_col) as [Count(D)],
sum([Count(E)]) Over(order by order_col) as [Count(E)]
From your_result
您可以在CASE
页面上添加sum over()
语句,以避免汇总type = Total
对于年长的诽谤
SELECT type,
cs.[Count(A)],
cs.[Count(B)],
cs.[Count(C)],
cs.[Count(D)],
cs.[Count(E)]
FROM your_result t
CROSS apply (SELECT Sum([Count(A)]) [Count(A)],
Sum([Count(B)]) [Count(B)],
Sum([Count(C)]) [Count(C)],
Sum([Count(D)]) [Count(D)],
Sum([Count(E)]) [Count(E)]
FROM your_result t1
WHERE t1.order_col <= t.order_col) cs