SQL累积总和,直到一个标志值并重置总和

时间:2019-01-17 15:18:10

标签: sql sql-server

我仍在学习SQL,并且试图找出我无法解决的问题。所以我的问题是我试图选择一个按日期排序的表(假设费用),并且在表中我有一列名为Charged,我想添加要累积的费用(这是我想出的这一部分)。但是,在那之后,我还有另一列将充当名为PayOut的标志。当PayOut值为1时,我希望Charged(SumValue)的总和重置为零。我该怎么做?这是我尝试过的,得到的当前输出以及想要的输出。注意:我看到了一些使用CTE的帖子,但是情况不一样,更复杂。

select ex.date, 
       ex.Charged,
       (case when(ex.PayOut=1) then 0 
             else sum(ex.Charged) over (order by ex.date)end) as SumValue, 
      ex.PayOut
from Expense ex 
order by ex.date asc

数据看起来像这样

Date       Charged   PayOut
01/10/2018   10        0
01/20/2018   5         0
01/30/2018   3         0
02/01/2018   0         1
02/11/2018   12        0
02/21/2018   15        0

我得到的输出

Date       Charged   PayOut  SumValue
01/10/2018   10        0        10
01/20/2018   5         0        15
01/30/2018   3         0        18
02/01/2018   0         1        0
02/11/2018   12        0        30
02/21/2018   15        0        45

想要的输出

Date       Charged   PayOut  SumValue
01/10/2018   10        0        10
01/20/2018   5         0        15
01/30/2018   3         0        18
02/01/2018   0         1        0
02/11/2018   12        0        12
02/21/2018   15        0        27

1 个答案:

答案 0 :(得分:4)

只需在“付款”列中创建组并将其用作OVER中的分区

WITH Expense AS (
              SELECT CAST('01/10/2018' AS DATE) AS Date, 10 AS Charged, 0 AS PayOut
    UNION ALL SELECT CAST('01/20/2018' AS DATE), 5, 0
    UNION ALL SELECT CAST('01/30/2018' AS DATE), 3, 0
    UNION ALL SELECT CAST('02/01/2018' AS DATE), 0, 1
    UNION ALL SELECT CAST('02/11/2018' AS DATE), 12, 0
    UNION ALL SELECT CAST('02/21/2018' AS DATE), 15, 0
)
SELECT
     dat.date
    ,dat.Charged
    ,dat.PayOut
    ,dat.PayOutGroup
    ,SUM(dat.Charged) OVER (PARTITION BY dat.PayOutGroup ORDER BY dat.date) as SumValue
FROM (
    SELECT 
         e.date
        ,e.Charged
        ,e.PayOut
        ,SUM(e.PayOut) OVER (ORDER BY e.date) AS PayOutGroup
    FROM Expense e
) dat