无法使用SQL滞后值

时间:2018-11-23 04:54:33

标签: sql sql-server sum lag

我的查询就是这样

SELECT
    [day], [time],AvaliableTimes,
    CASE
       WHEN AvaliableTimes > 0 
          THEN SUM(AvaliableTimes) OVER (ORDER BY [day], [time], AvaliableTimes)
          ELSE 0 
    END AS SumValue
FROM
    [AvailableTimes] 
WHERE
    [day] = 1 AND BranchAreaId = 1
ORDER BY
    [day], [time], AvaliableTimes

如果值是null或0,我想从0开始求和。

结果:

Attached Image below

1 个答案:

答案 0 :(得分:0)

您可以使用递归CTE来做到这一点。在rcte中执行累积总和,如果AvailableTimes = 0,则将其重置

; with
cte as
(
    select  *, rn = row_number() over (order by time)
    from    yourtable   
),
rcte as
(
    select  *, sumvalues = AvailableTimes
    from    cte
    where   rn = 1

    union all

    select  c.*, sumvalues = case when  c.AvailableTimes <> 0
                      then  r.sumvalues + c.AvailableTimes
                      else  c.AvailableTimes
                      end
    from    cte c
        inner join rcte r   on  c.rn    = r.rn + 1
)
select  day, time, AvailableTimes, sumvalues
from    rcte
order by time