sql - 如何查找日期范围内的出现次数?
问题描述
假设我在表 TestData 中有医院就诊
我想知道哪些患者在第一次就诊后的 7 天内第二次就诊。
我将如何在 SQL 中对此进行编码?我有 Patient_id 作为 TEXT,日期是 date_visit 也是 TEXT,格式为 MM/DD/YYYY
患者编号 | 日期访问 |
---|---|
A123B29133 | 2011 年 7 月 12 日 |
A123B29133 | 2011 年 7 月 14 日 |
A123B29133 | 2011 年 7 月 20 日 |
A123B29134 | 2016 年 12 月 5 日 |
在上表中,患者 A123B29133 符合 2011 年 7 月 14 日所见的条件,距 2011 年 7 月 12 日不到 7 天
解决方案
您可以使用子查询exists
:
with to_d(id, v_date) as (
select patient_id, substr(date_visit, 7, 4)||"-"||substr(date_visit, 1, 2)||"-"||substr(date_visit, 4, 2) from visits
)
select t2.id from (select t1.id, min(t1.v_date) d1 from to_d t1 group by t1.id) t2
where exists (select 1 from to_d t3 where t3.id = t2.id and t3.v_date != t2.d1 and t3.v_date <= date(t2.d1, '+7 days'))
ID |
---|
A123B29133 |