我有以下查询:
SELECT patient_id FROM patient_visit where visit_type in ('A', 'B', 'C')
group by patient_id having count(*) >= 2
获取至少两次“A”,“B”或“C”类型访问的所有患者的清单。
patient_visit表还有一个visit_date列,用于存储访问日期。我的问题:是否有可能修改上述查询而无需删除group by语句来查询“至少两次访问的所有患者以及这两次访问中的任何一个有60的差距 天数“?
谢谢!
P.S。:我正在使用Oracle,如果有内置函数,我也可以使用它。
答案 0 :(得分:3)
任何两个日期,所以第一次和最后一次访问都符合条件?
SELECT patient_id
FROM patient_visit
where visit_type in ('A', 'B', 'C')
group by patient_id
having count(*) >= 2 AND MAX(visit_date) - MIN(visit_date) >= 60
如果你的意思是连续的,那么
SELECT patient_id
FROM patient_visit
where visit_type in ('A', 'B', 'C')
AND EXISTS (
select *
from patient_visit v
where v.visit_type in ('A', 'B', 'C')
and v.patient_id = patient_visit.patient_id
and v.visit_date >= patient_visit.visit_date + 60)
AND NOT EXISTS (
select *
from patient_visit v2
where v2.visit_type in ('A', 'B', 'C')
and v2.patient_id = patient_visit.patient_id
and v2.visit_date > patient_visit.visit_date
and v2.visit_date < patient_visit.visit_date + 60)
group by patient_id
这是一个昂贵的查询,有点O(N 3 )。 Oracle LAG版本可能更快。
答案 1 :(得分:1)
SQL> create table patient_visit (patient_id number(38) not null
2 , visit_type varchar2(1) not null
3 , visit_date date not null);
Table created.
SQL> insert into patient_visit
2 select 1, 'A', date '2010-01-01' from dual
3 union all select 1, 'D', date '2010-01-02' from dual
4 -- ignore, by type
5 union all select 1, 'C', date '2010-01-01' + 60 from dual
6 -- 1 is included
7 union all select 1, 'B', date '2011-01-01' from dual
8 -- don't include 1 more than once
9 union all select 2, 'A', date '2010-01-01' from dual
10 union all select 2, 'B', date '2010-01-02' from dual
11 -- breaks up 60 day gap.
12 union all select 2, 'C', date '2010-01-01' + 60 from dual;
7 rows created.
SQL> commit;
Commit complete.
SQL> select patient_id
2 from (select patient_id
3 , visit_date
4 , lag(visit_date) over (partition by patient_id
5 order by visit_date) prior_visit_date
6 from patient_visit
7 where visit_type in ('A', 'B', 'C'))
8 where visit_date - prior_visit_date >= 60
9 group by patient_id;
PATIENT_ID
----------
1
SQL> spool off
答案 2 :(得分:0)
我没有oracle进行测试,但我认为这将有效
select patient_id from
(SELECT patient_id, dateField FROM patient_visit where visit_type in ('A','B', 'C')
group by patient_id having count(*) >= 2) as temp
where temp.dateField > '2011-01-01'