MS SQL窗口函数LAST_VALUE五秒钟

时间:2015-12-01 13:28:26

标签: sql-server sql-server-2012 window-functions

我已获得下一个数据ID,收到并平衡

现在我需要计算每个时间段的最后一列,因此最后一列应该是接下来五秒内余额列的最后一个值。

Id  Received    Balance     LastPerFiveSeconds
171 2015-11-25 10:05:50.630 13548830.86000000   15026517.59000000
172 2015-11-25 10:05:50.760 13590759.43000000   15026517.59000000
173 2015-11-25 10:05:50.790 13632688.00000000   15026517.59000000
174 2015-11-25 10:05:50.850 13662038.00000000   15026517.59000000
175 2015-11-25 10:05:50.910 13687195.15000000   15026517.59000000
176 2015-11-25 10:05:50.940 13703966.58000000   15026517.59000000
177 2015-11-25 10:05:50.950 13720738.01000000   15026517.59000000
178 2015-11-25 10:05:50.990 13762666.59000000   15026517.59000000
179 2015-11-25 10:05:51.060 13787823.73000000   15026517.68000000
180 2015-11-25 10:05:51.200 14987823.73000000   15026517.68000000
181 2015-11-25 10:05:51.360 15026517.68000000   15026517.68000000
182 2015-11-25 10:05:56.630 15034903.39000000   15034903.39000000

查询看起来像那样

SELECT id, Received, Balance, LAST_VALUE(Balance) OVER (PARTITION BY DATEADD(S, 5, [Received]) ORDER BY Received  RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)
FROM Data

1 个答案:

答案 0 :(得分:1)

您可以使用CROSS APPLY来实现您的目标。它将在未来查看最多五分钟的余额并选择最近的余额:

SELECT do.Id ,
      do.Received ,
      do.Balance ,
      ISNULL(details.Balance,do.Balance) AS LastPerFiveMinute
FROM      dbo.data do
      OUTER APPLY ( SELECT TOP 1
                         Balance
                 FROM    dbo.Data di
                 WHERE   di.Received <= DATEADD(MINUTE, 5,
                                            do.Received)
                         AND di.Received >= do.Received
                 ORDER BY    Received DESC
                ) details
ORDER BY Received ASC