根据日期标记添加计数

时间:2016-06-23 20:56:25

标签: sql

您能否就如何实现以下格式提出建议?我正在为这个问题思考解决方案。基本上,当flag为0时,将其求和并将其添加到标记为1的日期的下一个值 日期:

date         hrs_clock    some_flag    some_count
=================================================
6/20/2016    1            0            5
6/20/2016    2            0            6
6/20/2016    3            1            4
6/20/2016    4            1            2
6/20/2016    5            0            4
6/20/2016    6            0            6
6/21/2016    1            0            4
6/21/2016    2            0            3
6/21/2016    3            1            7
6/21/2016    4            1            2
6/21/2016    5            0            5
6/21/2016    6            0            4
6/22/2016    1            0            5
6/22/2016    2            0            5
6/22/2016    3            1            3
6/22/2016    4            1            2
6/22/2016    5            0            8
6/22/2016    6            0            4

结果:

date         hrs_clock    some_flag    some_count
=================================================
6/20/2016    3            1            15
6/20/2016    4            1             2
6/21/2016    3            1            24
6/21/2016    4            1             2
6/22/2016    3            1            22
6/22/2016    4            1             2
6/22/2016    5            0             8
6/22/2016    6            0             4

1 个答案:

答案 0 :(得分:1)

这很简单:

select 
    max(case when rn=1 then date else '1900-01-01' end) as date, 
    max(case when rn=1 then hrs_clock else -999 end) as hrs_clock, 
    max(some_flag) as some_flag, 
    sum(some_count) as some_count
from (
    select 
        *, row_number() over (
            partition by 
                case when flag_group=0 then date else flag_group end,
                case when flag_group=0 then hrs_clock else flag_group end
            order by date desc, hrs_clock desc
        ) [rn]
    from (
        select 
            *, 
            sum(cast(some_flag as int)) over (
                order by date desc, hrs_clock desc 
                rows unbounded preceding) [flag_group]        
        from log
    ) x
) xx
group by case when flag_group=0 then [date] else flag_group end,
         case when flag_group=0 then hrs_clock else flag_group end

order by date, hrs_clock