在子查询中保持运行总计并返回计数 - SQL Server

时间:2017-08-09 21:22:04

标签: sql-server

我想创建一个保持运行总计的子查询,并返回运行总计超过4.99的次数。

+------------+------------+---------------+-------+
|    Date    | Occurrence | Running Total | Count |
+------------+------------+---------------+-------+
| 5/21/2017  |      0.25  |          6.75 |     6 |
| 5/9/2017   |         1  |           6.5 |     5 |
| 5/8/2017   |         0  |           5.5 |     4 |
| 4/17/2017  |      0.25  |           5.5 |     3 |
| 3/15/2017  |      0.25  |          5.25 |     2 |
| 2/15/2017  |      0.25  |             5 |     1 |
| 1/6/2017   |      0.25  |          4.75 |       |
| 12/19/2016 |      0.25  |           4.5 |       |
| 12/14/2016 |      0.25  |          4.25 |       |
| 12/6/2016  |      0.25  |             4 |       |
| 12/2/2016  |         1  |          3.75 |       |
| 12/1/2016  |         1  |          2.75 |       |
| 11/17/2016 |      0.25  |          1.75 |       |
| 10/17/2016 |         1  |           1.5 |       |
| 9/29/2016  |      0.25  |           0.5 |       |
| 9/28/2016  |      0.25  |          0.25 |       |
| 9/13/2016  |         0  |             0 |       |
+------------+------------+---------------+-------+

根据我提供的示例数据,我希望查询返回6的int。

我所拥有的表有两列,包括日期和事件。

选择语句的示例:

SELECT [Date], [Occurrence]
FROM TimeUsage
WHERE [Date] >= DATEADD(YEAR, -1, GETDATE())
ORDER BY [DATE] DESC

我想在另一个SQL查询中使用此代码。

1 个答案:

答案 0 :(得分:1)

使用窗口功能计算运行总计

SELECT COUNT(RunningTotal) 
FROM (
     SELECT SUM(Occurance) OVER (ORDER BY Date) as RunningTotal
     FROM YourTable
) as T
WHERE RunningTotal > 4.99