如何在sqlite中查找剩余的日期范围

m528fe3b  于 2023-04-12  发布在  SQLite
关注(0)|答案(1)|浏览(215)

我有一个sqlite数据库,像

ID起始日期至今
1 2023-04-02 2023-04-07

2023-04-05 2023-04-06
2023-04-09 2023-04-11

**2 2023-04-09 2023-04-16

从temptable。
现在我正在使用stack在 sqlite 中创建查询
当我搜索日期从2023-04-02到2023-04-30时,每个ID的剩余日期范围应该填充。

预期输出
ID起始日期至今
**1 2023-04-08 2023-04-30
2 2023-04-02 2023-04-04
2 2023年4月7日2023年4月8日
2 2023-04-17 2023-04-30

2023-04-02 2023-04-08
2023-04-12 2023-04-30
请帮帮我
我尝试了许多事情,但都失败了

bvuwiixz

bvuwiixz1#

对于每个ID,您需要在所需期间内原始间隔集未覆盖的天数间隔。
假设你的原始区间在同一个id中没有重叠。找到左、右区间和并集

with tbl(ID, Fromdate, Todate) as (
  -- sample data
  select 1, julianday('2023-04-02'), julianday('2023-04-07') union all
  select 2, julianday('2023-04-05'), julianday('2023-04-06') union all
  select 3, julianday('2023-04-09'), julianday('2023-04-11') union all
  select 2, julianday('2023-04-09'), julianday('2023-04-16') 
),
params (ds, de) as (
  -- period to search within
  select julianday('2023-04-02'), julianday('2023-04-30')
), 
leftintvls as (
  -- the closest end of intervals relative to current interval start
  select id,  
    (select max(t2.Todate)+1  
     from tbl t2 
     where t2.id = t.id and t2.Todate < t.Fromdate ) ms, Fromdate-1 me
  from tbl t
  -- only itervals overlapping with the requierd period
  join params p on t.Fromdate <= p.de and p.ds <= t.Todate 
    --  starting later than required period starts
    and t.Fromdate > p.ds
),
rightintvls as (
  -- the closest start of interval relative current interval end
  select id, Todate+1 ms,  
    (select min(t2.Fromdate) - 1  
     from tbl t2 
     where t2.id = t.id and t2.Fromdate > t.Todate ) me
  from tbl t
  -- only itervals overlapping with the requierd period
  join params p on t.Fromdate <= p.de and p.ds <= t.Todate 
     --  ending earlier than required period ends
     and t.Todate < p.de  
)
select id, date(ifnull(ms, p.ds)) fromd, date(me) tod
from leftintvls
cross join params p
where ifnull(ms, p.ds) <= me  
  
union 
  
select id, date(ms),  date(ifnull(me, p.de))
from rightintvls
cross join params p
where ms <= ifnull(me, p.de)
order by id, fromd

db<>fiddle

相关问题