我有一张包含 ID 和日期的表格。第一个日期应充当十天块的开始计时器,其中接下来十天内的任何记录都应计为单个实例。初始 10 天块之外的任何后续记录都应计为新实例,并用作新 10 天块的启动计时器。
关于如何构建查询以获得与此类似的输出有什么想法吗?
身份证 | 日期 | 数 |
---|---|---|
123456 | 8/22/23 | 1 |
123456 | 8/23/23 | 0 |
123456 | 8/29/23 | 0 |
123456 | 9/04/23 | 1 |
123456 | 9/08/23 | 0 |
123456 | 9/16/23 | 1 |
我从来没有处理过滑动时间块/间隔,所以这是第一次挫败感。任何帮助将不胜感激!
您需要某种迭代解决方案。逐行游标是一种简单的方法。这是一些基于集合的循环伪代码:
while exists (select 1 from T where "count" is null) -- assumes that null means unmarked
begin
update T
set "count" = -1 -- temporarily mark the new windows as -1
where "count" is null and not exists (
select 1 from T t2
where t2."date" between T."date" - 9 days and T."date" and t2."count" is null
);
update T
set "count" = case "count" when -1 then 1 else 0 end
where "count" = -1 or "count" is null and exists (
select 1 from T t2
where t2."date" between T."date" - 9 days and T."date" and t2."count" = -1
);
end