2016-10-17 3 views
0

私は多くの一時テーブルの結果であるテーブルを持っており、それはjoinとorder by節を含んでいます。現在の行に前の行を追加する - SQL Server 2008

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 

Iは、以下のように出力したい: 現在の行の値は、それが合計に一致するまでに前の行値+電流value..sooであるべきです。

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使用してtable.Kindly help.Iを導出することはできませんが、クエリを使用している:実行している計算に

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

答えて

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文を追加することができます。

古いVerionsについては

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 
+0

これは、私のために働いていない – Ruchi

+0

それは最初のテーブルと同じ数を与えます。.. – Ruchi

関連する問題