-4

テーブルには次のようなデータがあります

<--------------------------->  
no      category     value 
<--------------------------->      
1        1           2000    
2        1           1000     
3        2            500    
4        3           3000    
5        1           2000   
6        2           -500        
7        3           5000    
8        1          -1000 

そして、私は次のような出力が欲しい

<----------------------------------> 
no  category     amount       Sum   
<---------------------------------->   
1        1       2000         2000                
2        1       1000         3000                 
3        2        500          500                 
4        3       3000         3000                 
5        1       2000         5000                  
6        2       -500            0                 
7        3       5000         8000
8        1      -1000         4000 

例:category=1 そうしてください、

no:1
amount=2000--->total=2000
no:2
amount=1000---->total=3000
no:5
amount=2000---->total=5000
no:8
amount=-1000---->total=4000

これは、すべての行の各カテゴリの合計であり、パフォーマンスが向上していることを意味します

4

3 に答える 3

0

必要なのは、ローリング合計を計算することです。私が知っている SQL Server 2005/2008/2008 R2 での最速の方法は、https ://stackoverflow.com/a/13744550/1744834 で説明されています。このメソッドを使用するには、次のように、各カテゴリ内に一意の連続列が必要です。

create table #t (no int, category int, value int, id int, primary key (category, id))

insert into #t (no, category, value, id)
select no, category, value, row_number() over (partition by category order by no)
from test

;with 
CTE_RunningTotal
as
(
    select T.no, T.category, T.value, cast(T.value as decimal(29, 10)) as total_value, T.id
    from #t as T
    where T.id = 1
    union all
    select T.no, T.category, T.value, cast(T.value + C.total_value as decimal(29, 10)) as total_value, T.id
    from CTE_RunningTotal as C
        inner join #t as T on T.id = C.id + 1 and T.category = C.category
)
select C.no, C.category, C.value, C.value
from CTE_RunningTotal as C
option (maxrecursion 0)

SQL フィドルの例

より短いクエリを使用することもできますが、パフォーマンスは低下します (再帰 CTE では O(N^2) 対 O(N) だと思います):

select t1.no, t1.category, t1.value, sum(t2.value)
from test as t1
    inner join test as t2 on t2.category = t1.category and t2.no <= t1.no
group by t1.no, t1.category, t1.value
order by t1.no

SQL フィドルの例

于 2013-07-30T11:27:29.827 に答える
-1

次のSQL関数を使用できます。SQL関数は、その使用方法と適用方法を示しています

于 2013-07-30T10:57:01.540 に答える