假设我有一个奖励SQL表,其中包含Date和Amount字段。我需要生成一系列连续日期,每天奖励金额和运行(累计)总额的表格。改进SQL查询:随着时间推移的累计金额
Date Amount_Total Amount_RunningTotal
---------- ------------ -------------------
1/1/2010 100 100
1/2/2010 300 400
1/3/2010 0 400
1/4/2010 0 400
1/5/2010 400 800
1/6/2010 100 900
1/7/2010 500 1400
1/8/2010 300 1700
这个SQL工作,但没有那么快,我想:
Declare @StartDate datetime, @EndDate datetime
Select @StartDate=Min(Date), @EndDate=Max(Date) from Awards
; With
/* Returns consecutive from numbers 1 through the
number of days for which we have data */
Nbrs(n) as (
Select 1 Union All
Select 1+n
From Nbrs
Where n<=DateDiff(d,@StartDate,@EndDate)),
/* Returns all dates @StartDate to @EndDate */
AllDays as (
Select Date=DateAdd(d, n, @StartDate)
From Nbrs)
/* Returns totals for each day */
Select
d.Date,
Amount_Total = (
Select Sum(a.Amount)
From Awards a
Where a.Date=d.Date),
Amount_RunningTotal = (
Select Sum(a.Amount)
From Awards a
Where a.Date<=d.Date)
From AllDays d
Order by d.Date
Option(MAXRECURSION 1000)
我尝试添加一个索引Awards.Date,但它使一个很小的差别。
在我使用缓存等其他策略之前,有没有更有效的方法来编写运行总计算?
非常感谢 - 这是完美的。惊人的速度如此之快。 – 2010-01-10 18:57:04
我以前从来没有见过类似“SET @x = a = @x + b”的语法。为什么RDBMS能做到这一点? – MatBailie 2010-01-10 19:03:17
@Dems:此语法适用于SQL Server,但您可以在mysql中执行一些非常类似的操作(请参阅我的答案底部附近的链接 - 某人发布了mysql版本的位置)。 – Aaronaught 2010-01-10 19:26:23