难以概念化 sql 个查询

difficulty conceptualizing sql query

我对当前的报告问题有点困惑,希望能得到一些帮助。

一位医生即将退休。她的病人需要被告知她退休了。构成"her patient"的人在过去两年里看过她的次数比任何其他医生都多。如果做不到这一点(即在过去 2 年里,她和另一位医生各看过 2 次),他们 "her patient" 如果他们最近去看她。

这是我目前所拥有的。

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 有一个且只有一个 performing_md_id 表明患者的医生(医生他们这两年看的次数最多的,如果不是那个,就是最近看的医生)。

我假设您有一个 table 形状为患者、医生、访问日期

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])

像这样。 table 和列名是组合的,但应该是不言自明的。

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
;