2016-06-23 53 views
-4

您能否就如何实现以下格式提供建议?我正在为这个问题失去思考的解决方案。基本上,其中标志为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 
+0

'... SUM(some_count)作为ct GROUP BY日期,hrsc_clock,some_flag'? – dognose

+2

您将需要包含更多解释,而不仅仅是“帮助我使它看起来像这样”。 –

+2

我没有按照你期望的结果集背后的逻辑.. – Siyual

回答

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