基于sql中日期范围的滚动总和

时间:2018-04-10 21:49:03

标签: sql sql-server hana

寻找性能有效的SQL代码,根据DATE Sum计算Rolling Sum。我的数据如下:

+----+-----------+----+
| ID |   Date    | Qt |
+----+-----------+----+
|  1 | 1/12/2009 |  2 |
|  2 | 1/13/2009 |  3 |
|  3 | 1/14/2009 | 10 |
|  4 | 1/15/2009 |  2 |
|  5 | 1/16/2009 |  3 |
|  6 | 1/17/2009 |  7 |
|  7 | 1/18/2009 |  5 |
|  8 | 1/19/2009 |  4 |
|  9 | 1/20/2009 |  2 |
| 10 | 1/21/2009 |  3 |
| 11 | 1/22/2009 | 10 |
| 12 | 1/23/2009 |  2 |
| 13 | 1/24/2009 |  3 |
| 14 | 1/25/2009 |  7 |
| 15 | 1/26/2009 |  5 |
| 16 | 1/27/2009 |  4 |
| 17 | 1/28/2009 |  1 |
| 18 | 1/29/2009 |  0 |
| 19 | 1/30/2009 |  8 |
| 20 | 1/31/2009 |  9 |
+----+-----------+----+

输出应该是:

+----+-----------+----+-----------+
| ID |   Date    | Qt | Roll10Day |
+----+-----------+----+-----------+
|  1 | 1/12/2009 |  2 |         2 |
|  2 | 1/13/2009 |  3 |         5 |
|  3 | 1/14/2009 | 10 |        15 |
|  4 | 1/15/2009 |  2 |        17 |
|  5 | 1/16/2009 |  3 |        20 |
|  6 | 1/17/2009 |  7 |        27 |
|  7 | 1/18/2009 |  5 |        32 |
|  8 | 1/19/2009 |  4 |        36 |
|  9 | 1/20/2009 |  2 |        38 |
| 10 | 1/21/2009 |  3 |        41 |
| 11 | 1/22/2009 | 10 |        49 |
| 12 | 1/23/2009 |  2 |        48 |
| 13 | 1/24/2009 |  3 |        41 |
| 14 | 1/25/2009 |  7 |        46 |
| 15 | 1/26/2009 |  5 |        48 |
| 16 | 1/27/2009 |  4 |        45 |
| 17 | 1/28/2009 |  1 |        41 |
| 18 | 1/29/2009 |  0 |        37 |
| 19 | 1/30/2009 |  8 |        43 |
| 20 | 1/31/2009 |  9 |        49 |
+----+-----------+----+-----------+

我们可以使用窗口功能实现吗?我知道我可以在SQL中使用内部查询。

3 个答案:

答案 0 :(得分:1)

通常使用带有sum()的窗口子句来处理:

select t.*,
       sum(qt) over (order by date rows between 9 preceding and current row)
from t;

我不知道SAP Hana是否支持这种语法。 SQL Server可以。

答案 1 :(得分:1)

您可以执行以下操作来满足行与行之间没有连续日期的情况。


SELECT 
t1.Id
,t1.Date
,t1.Qt
,SUM(t2.Qt) as Rolling10DayQt
FROM [your-table] t1

    CROSS APPLY (
        SELECT *
        FROM [your-same-table] a
        WHERE a.Id= t1.Id 
              AND (a.Date > DATEADD(DAY,-10,t1.Date) AND a.Date <= t1.Date) ) t2

GROUP BY t1.Id ,t1.Date ,t1.Qt

希望有帮助。

答案 2 :(得分:0)

试试这个......

select
 ID
,Date
,Qt
,SUM(Qt) OVER (ORDER BY  ID  ROWS BETWEEN UNBOUNDED PRECEDING  AND  0  PRECEDING) AS 'Roll10Day'
from [TABLE NAME]