如何在表

时间:2016-11-21 06:00:59

标签: sql teradata

给定一个表包含这些数据

Enrolid  Dtstart       Preceding Dtend        
001      2000-02-01    2000-01-13     
001      2000-03-01    2000-02-29
001      2000-04-01    2000-03-31
001      2000-07-01    2000-04-30
001      2000-09-01    2000-07-31
002      2000-03-01    2000-02-29
002      2000-04-01    2000-03-31
002      2000-07-01    2000-04-30
002      2000-09-01    2000-07-31

如何从1开始生成一个新字段作为计数器 当Dtstart - Pretend Dtend> 31,counter = counter + 1 否则没有变化。理想情况下,它可以由EnrolId重置。

结果将是:

Enrolid  Dtstart       Preceding Dtend      Counter  
001      2000-02-01    2000-01-13           1
001      2000-03-01    2000-02-29           1
001      2000-04-01    2000-03-31           1
001      2000-07-01    2000-04-30           2
001      2000-09-01    2000-07-31           3
002      2000-03-01    2000-02-29           1
002      2000-04-01    2000-03-31           1
002      2000-07-01    2000-04-30           2
002      2000-09-01    2000-07-31           3

我尝试使用存储过程,并运行如下的循环"

for loopvar as cur1 cursor for 
  select enrolid, dtstart, dtstart-preceding_dtend as gap 
  from dc_rwd_omop.temp_observation_period 
  order by enrolid, dtstart

    do 
        if (loopvar.gap is not null and loopvar.gap > 31) then

            set counter = counter +1; 
        end if;
end for;

但是,由于该表包含数十亿条记录,因此效率不高。

有想法有效率的方法吗?

1 个答案:

答案 0 :(得分:2)

select      Enrolid,Dtstart,"Preceding Dtend"   

           ,count(case when Dtstart - "Preceding Dtend" > 31 then 1 end) over
            (
                partition by Enrolid
                order by     Dtstart
                rows         unbounded preceding
            ) 
          + case    
                when    first_value (Dtstart - "Preceding Dtend") over
                        (
                            partition by Enrolid
                            order by     Dtstart
                            rows         unbounded preceding
                        ) > 31 
                then    0
                else    1
            end             as Counter                    

from        t