如何在 table 中创建增量计数器
How to create an incremental counter in a table
给定一个 table 包含这些数据
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 - Preceding 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;
但是,由于 table 包含数十亿条记录,因此效率不高。
有什么有效的方法吗?
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
给定一个 table 包含这些数据
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 - Preceding 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;
但是,由于 table 包含数十亿条记录,因此效率不高。
有什么有效的方法吗?
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