显示不包含特定值的所有用户

时间:2014-03-11 19:24:33

标签: sql-server-2005 max where

我需要一种方法来获取所有没有PCP关系的患者的清单,即使患者有多种关系。这种关系也必须在当前的情节中。提前致谢,我正在运行SQL Server 2005

select 

distinct r.patient_id, 
r.episode_id, 
r.relation

from 
(select r.*, max(episode_id) over (partition by patient_id) as maxei from relationship r) r
join patient_custom pc
on r.patient_id = pc.patient_id
where health_home = 'y' --and r.relation = 'PCP'
order by r.patient_id, r.relation

enter image description here

1 个答案:

答案 0 :(得分:1)

我认为这样可行......见内联评论。

SELECT
    PatientEpisode.Patient_ID,
    PatientEpisode.Epsode_ID

FROM (
    -- Find the list of patients and their current episode
    SELECT r.Patient_ID, MAX(r.Episode_ID) AS Episode_ID
    FROM Relationship r
       JOIN patient_custom pc
       ON r.Patient_ID = pc.Patient_ID
    WHERE pc.Health_Home = 'y'
    GROUP BY r.Patient_ID
) PatientEpisode

-- Now exclude any patients that DO have a "PCP" 
-- relationship in their current episode.
WHERE NOT EXISTS (
    SELECT *
    FROM Relationship
    WHERE Patient_ID = PatientEpisode.Patient_ID
    AND Episode_ID = PatientEpisode.Episode_ID
    AND Relation = 'PCP'
)

修改 我添加了Health_Home过滤器。要了解其工作原理,请首先单独运行此SELECT

    SELECT r.Patient_ID, MAX(r.Episode_ID) AS Episode_ID
    FROM Relationship r
       JOIN patient_custom pc
       ON r.Patient_ID = pc.Patient_ID
    WHERE pc.Health_Home = 'y'
    GROUP BY r.Patient_ID

您会看到它会返回所有患者以及每位患者最近一次的情况。

然后,一旦掌握了这些数据,就会将其包含在SQL的其余部分中,以过滤掉当前PCP关系的患者。