难以概念化SQL查询

时间:2016-11-03 16:30:09

标签: sql oracle selection

我对当前的报道问题感到有点紧张,我希望能找到一些帮助。

医生正在退休。需要通知她的患者退休。在过去两年中,构成“她的病人”的人比其他任何医生都看过她多次。如果不这样做(例如,在过去的两年里,她已经看过她和另一位医生2次),如果他们最近去看她,她们就是“她的病人”。

到目前为止,这就是我所拥有的。

select patient_id, last_name, first_name, post_fromdate, performing_md_id, performing_md_name, category_desc, procedure_code
from [table]
where post_fromdate >= ADD_MONTHS(SYSDATE,-24)
and category_desc like '%WELL%' --specific visit type
and patient id in ([list of patients])
group by patient_id, last_name, first_name, post_fromdate, performing_md_id, performing_md_name, category_desc, procedure_code
order by patient_id, post_fromdate desc

回顾......

我所拥有的:每位医生都会拜访所有相关医生的病人,包括去看其他医生。

我寻求的是:一些额外的标准,表明退休医生是否被每个患者最多访问。如果看到同样但不低于给定患者的其他医生,那么如果最近就去过退休医生那么。

任何帮助都是慷慨接受的。提前谢谢。

编辑:输出所需的结果,为我提供select子句中的信息,每个patient_id只有一个perform_md_id,表示患者的医生(他们在过去两年中看过的次数最多的医生。如果不是那就是他们最近见过的医生。)

2 个答案:

答案 0 :(得分:1)

像这样的东西。表和列名称是由组成的,但应该是不言自明的。

select patient_id, 
       max(doctor_id) keep (dense_rank last order by ct, last_visit) as primary_doctor_id
from   (
         select   patient_id, doctor_id, count(*) as ct, max(visit_date) as last_visit
         from     visits
         group by patient_id, doctor_id
       )
group by patient_id
;

答案 1 :(得分:0)

我假设你有一张患者,医生,访问日期的表格

select patient,[This Doc] as [This DOC Visit Count], [Other Doc] as [Other Doc Visit Count]
into #visit_counts
from (select patient, case when doctor = 'retiring doc' then 'This Doc' else 'Other Doc' end as Doc, visit_date from doc_patient_visit_table ) P
Pivot (count(visit_date) for Doc in ([This Doc],[Other Doc])) Pvt

select patient,[This Doc] as [This DOC Last Visit], [Other Doc] as [Other Doc Last visit]
into #visit_times
from (select patient, case when doctor = 'retiring doc' then 'This Doc' else 'Other Doc' end as Doc, visit_date from doc_patient_visit_table) P
Pivot (max(visit_date) for Doc in ([This Doc],[Other Doc])) Pvt

select patient, [This DOC Visit Count],  [Other Doc Visit Count], [This DOC Last Visit], [Other Doc Last visit]
from #visit_counts t1
join #visit_times t2 on t1.patient = t2.patient
where [This DOC Visit Count] > [Other Doc Visit Count] or ([This DOC Visit Count] = [Other Doc Visit Count] and [This DOC Last Visit] > [Other Doc Last visit])

另一种方法

Select patient, 
sum(case when doc = 'retiring_doc' then 1 else 0 end) as [This DOC Visit Count],
max(case when doc = 'retiring_doc' then visit_date end)  as [This DOC Last Visit],
sum(case when doc != 'retiring_doc' then 1 else 0 end) as [Other Doc Visit Count],
max(case when doc != 'retiring_doc' then visit_date end)  as [Other Doc Last visit]
from from doc_patient_visit_table
group by patient
having sum(case when doc = 'retiring_doc' then 1 else 0 end) > sum(case when doc != 'retiring_doc' then 1 else 0 end) 
OR (sum(case when doc = 'retiring_doc' then 1 else 0 end) = sum(case when doc != 'retiring_doc' then 1 else 0 end)
AND [This DOC Last Visit] > [Other Doc Last visit])