最后5行的累计总和

时间:2017-08-31 07:45:45

标签: sql tsql case where partition

我对SQL查询有疑问。 我需要根据Y列中的值计算X列中最后5行值的累计运行总数。列Y可以包含Yes,No或Maybe

数据示例如下:

   Date  Column X   Column Y   Yes cum total  No cum total Maybe Total

   31/8   1000      Y          1200           800          250
   30/8   500       N           250           800          250 
   29/8   200       Y           250           375          250
   28/8   300       N            50           375          250
   27/8   250       M            50            75          250
   26/8    50       Y            50            75           0 
   25/8    75       N            0             75           0

我已经尝试了案例和分区,但在每种情况下,当我指定where部分时,它不会给我累积值,而只是where where条件为true的值的总和。

非常感谢任何帮助。

Data table and required results

1 个答案:

答案 0 :(得分:2)

您可以将累积总和与case和窗口子句一起使用:

select t.*,
       sum(case when y = 'Y' then x else 0 end) over
           (order by date rows between 4 preceding and current row) as y,
       sum(case when y = 'N' then x else 0 end) over
           (order by date rows between 4 preceding and current row) as n,
       sum(case when y = 'M' then x else 0 end) over
           (order by date rows between 4 preceding and current row) as m
from t;