2012-07-25 48 views
0

我的记录是有三列临时表:SQL最快的基于阈值组的方式记录

  1. 列1:ID(BIGINT)
  2. 列2:CreationDateTime(DATETIME)
  3. 栏3:卷(Float)

记录根据CreationDateTime进行排序。 我需要从表格中选取体积总和等于THRESHOLD1,然后对于阈值2相同的记录。

一种方法是将新的列添加到具有以前记录的总和的表中。例如:

ID - CreationDateTime - 音量 - SUM

1 - 2012/7/20 - 10 - 10

2 - 21/07/2012 - 12 - 22

3 - 22/07/2012 - 7 - 29

然后选择* from temp其中Sum> = Threshold但是总和的计算并不是最快的方法。

我想知道是否有人可以提出一个更好的方法来做到上述。

我正在使用SQL Server 2008,如果需要,我也可以使用CLR。

回答

0

下面是一个使用递归CTE,一种方法,这将有可能是最快的:

select @i=min(ID) from @temp 

;with a as 
( 
    select ID, Volume, Volume as RunningTotal 
    from @temp 
    where [email protected] 

    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语句:

select * from dbo.MyVolumnTable where RunningTotal <= @Threshold1 
+0

你是否也请广告最后的答复?因为我也想检查它们。 thx – Asha 2012-07-25 11:33:47

+0

@Asha - 添加回参考文献 – 2012-07-25 11:51:08

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