【问题标题】:SQL Fastest way to Group records based on ThresholdsSQL 根据阈值对记录进行分组的最快方法
【发布时间】:2012-07-25 20:02:42
【问题描述】:

我的记录在一个包含三列的临时表中:

  1. 第 1 列:ID (Bigint)
  2. Column2:CreationDateTime(日期时间)
  3. 第 3 列:体积(浮点数)

记录根据 CreationDateTime 排序。 我需要从表中选择总和等于 THRESHOLD1 的记录,然后对于 Threshold2 也是如此。

一种方法是在表中添加一个新列,该列具有先前记录的 Volume 总和。例如:

ID - CreationDateTime - 卷 - 总和

1 - 20/07/2012 - 10 - 10

2 - 21/07/2012 - 12 - 22

3 - 22/07/2012 - 7 - 29

然后 Select * from temp where Sum >= Threshold 但是求和并不是最快的方法。

我想知道是否有人可以提出更好的方法来完成上述操作。

我使用的是 SQL Server 2008,如果需要,我也可以使用 CLR。​​

【问题讨论】:

    标签: sql-server-2008 tsql


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      这是一种使用递归 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 
      

      【讨论】:

      • 请问最后的回复好吗?因为我也想检查它们。谢谢
      • @Asha - 添加了引用
      猜你喜欢
      • 1970-01-01
      • 2011-03-28
      • 2021-07-20
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 2020-11-10
      • 2020-09-13
      相关资源
      最近更新 更多