累计总数基于条件

时间:2015-06-19 18:02:42

标签: sql-server-2008 conditional

我试图根据某些标准获得累计总数。下面是一个虚拟样本数据集。我想根据IndicatorID获得累计时间。如果同一Indicator的{​​{1}}持续1,我希望获得所有ID的总和。如果它变为Duration,那么我想重新启动。

0

1 个答案:

答案 0 :(得分:0)

数据:

DECLARE @t TABLE
    (
      ID INT ,
      Duration INT ,
      INDICATOR INT
    )
INSERT  INTO @t
VALUES  ( 1, 30, 0 ),
        ( 1, 30, 1 ),
        ( 1, 30, 0 ),
        ( 1, 30, 0 ),
        ( 1, 30, 1 ),
        ( 1, 30, 0 ),
        ( 1, 30, 0 ),
        ( 1, 30, 0 ),
        ( 1, 30, 0 ),
        ( 1, 30, 0 ),
        ( 1, 30, 0 ),
        ( 1, 30, 0 ),
        ( 1, 30, 1 ),
        ( 1, 30, 1 ),
        ( 2, 30, 1 ),
        ( 2, 30, 0 ),
        ( 2, 30, 0 ),
        ( 2, 30, 0 ),
        ( 2, 30, 1 ),
        ( 2, 30, 0 ),
        ( 2, 30, 1 ),
        ( 2, 30, 0 ),
        ( 2, 30, 0 ),
        ( 2, 30, 0 ),
        ( 2, 30, 1 ),
        ( 2, 30, 1 ),
        ( 2, 30, 0 );

解决方法1(暴力破解):

with    indexed
          as ( select   * ,
                        row_number() over ( order by ( select null ) ) rn
               from     @t
             ),
        recursion
          as ( select   * ,
                        duration as cumulative
               from     indexed
               where    rn = 1
               union all
               select   t.* ,
                        case when t.indicator = 1 and t.id = r.id
                             then r.cumulative + t.duration
                             else t.duration
                        end
               from     indexed t
                        join recursion r on r.rn + 1 = t.rn
             )
    select  * from    recursion
    option  ( maxrecursion 0 )

溶液2:

with indexed as (select *, row_number() over (order by (select null)) rn from @t)
select *,
       (select sum(duration) from indexed i2
        where i1.id = i2.id and i2.rn <= i1.rn and 
              i2.rn >= isnull((select top 1 i3.rn from indexed i3
                               where i3.indicator = 0 and i3.rn <= i1.rn
                               order by i3.rn desc), 0))
from indexed i1
相关问题