0

私のレコードは、3 つの列を持つ一時テーブルにあります。

  1. 列 1 : ID (Bigint)
  2. Column2 : CreationDateTime (dateTime)
  3. Column3 : ボリューム (フロート)

レコードは CreationDateTime に基づいてソートされます。ボリュームの合計が THRESHOLD1 に等しく、次に Threshold2 も同じであるテーブルからレコードを選択する必要があります。

1 つの方法は、前のレコードのボリュームの合計を持つテーブルに新しい列を追加することです。例えば ​​:

ID - CreationDateTime - ボリューム - SUM

1 - 2012 年 7 月 20 日 - 10 - 10

2 - 2012 年 7 月 21 日 - 12 - 22

3 - 2012 年 7 月 22 日 - 7 - 29

Select * from temp where Sum >= Threshold しかし、合計の計算は最速の方法ではありません。

上記を行うためのより良い方法を誰かが提案できるかどうか疑問に思っていました。

私は SQL Server 2008 を使用していますが、必要に応じて CLR も使用できます。

4

2 に答える 2

1

この解決策を試してください:

テーブルを自己結合してグループ化するだけで、現在の合計を見つけることができます

with cte as(
select T2.ID, T2.CreationDateTime,SUM(T1.Volume) [SUM]
from test_table T1 join  test_table T2
on T1.id<=T2.id
group by T2.id, T2.CreationDateTime)
select * from cte where [SUM]>= Threshold
于 2012-07-25T10:44:47.967 に答える
0

これは再帰的な CTE を使用したアプローチで、おそらく最も高速です。

select @i=min(ID) from @temp

;with a as 
( 
    select ID, Volume, Volume as RunningTotal 
    from @temp
    where ID=@i 

    union all 
    select b.ID, b.Volume, b.Volume + a.RunningTotal as RunningTotal 
    from @temp b 
        inner join a 
            on b.ID=a.ID+1 

) 
select * from a 

累計に関連するいくつかのリンク:

http://www.sqlusa.com/bestpractices/runningtotal/

http://www.databasejournal.com/features/mssql/article.php/3112381/SQL-Server-Calculating-Running-Totals-Subtotals-and-Grand-Total-Without-a-Cursor.htm

http://www.mssqltips.com/sqlservertip/1686/calculate-running-totals-using-sql-server-cross-joins/

http://social.msdn.microsoft.com/Forums/eu/transactsql/thread/1b4d87cb-ec77-4455-af48-bf7dae50ab87

関数を使用した計算列:

create function dbo.fn_VolumeRunningTotal 
{ 
    @dt datetime 
} 
returns int 
as  
begin 
    declare @total int 
    select @total = sum(volume) 
    from dbo.MyVolumeTable 
    where CreationDateTime <= @dt 

    return @total 
end 

計算列の式:

dbo.fn_VolumeRunningTotal(CreationDateTime) 

ステートメントを選択します。

select * from dbo.MyVolumnTable where RunningTotal <= @Threshold1 
于 2012-07-25T10:29:01.390 に答える