比较同一列和同一表中的行

时间:2018-10-03 18:45:05

标签: sql sql-server

我有以下查询

select em.ClinicCode,pa.ConsultantID,pa.RegCode as MRN, pa.AdmissionID,pa.AdmitDate,bm.PainScoreID,pn.PainScore from v_dbPatientAdmissions pa
inner join v_dbPatientBodyMass bm on bm.AdmissionID=pa.AdmissionID
inner join v_dbPainScores pn on bm.PainScoreID=pn.PainScoreID
inner join v_dbEmpClinicCodes em on em.EmpID=pa.ConsultantID
where pa.ConsultantID=1108

给出以下输出: enter image description here

我已经使用内部联接将三个表与主表'v_dbPatientAdmissions'联接在一起,以便检索特定医生已经看到的痛苦患者。

我正在尝试检索在不到24小时内返回诊所的患者的记录,我需要比较同一列“ AdmitDate”中的两行,同时使用“ MRN”,我想Datediff函数的功能,但是当我尝试比较同一列中的行时,我不确定该怎么做

2 个答案:

答案 0 :(得分:2)

对于SQL Server 2012+,您可以使用函数LAG和/或LEAD

假设您只需要检索第二条记录,则可以使用以下内容:

select 
    em.ClinicCode, 
    pa.ConsultantID,
    pa.RegCode as MRN, 
    pa.AdmissionID,
    pa.AdmitDate,
    bm.PainScoreID,
    pn.PainScore 
from v_dbPatientAdmissions pa
inner join v_dbPatientBodyMass bm on bm.AdmissionID=pa.AdmissionID
inner join v_dbPainScores pn on bm.PainScoreID=pn.PainScoreID
inner join v_dbEmpClinicCodes em on em.EmpID=pa.ConsultantID
where pa.ConsultantID=1108
    and DATEDIFF('hour', 
        LAG(pa.AdmitDate, 1, '1900-01-01') OVER (PARTITION BY pa.RegCode ORDER BY pa.AdmitDate), 
        pa.AdmitDate) < 24

我不确定哪个字段代表唯一的患者字段,但我认为它是pa.RegCode

为了检索同一位患者的先前就诊日期,我使用了LAG函数:

LAG(pa.AdmitDate, 1, '1900-01-01') OVER (PARTITION BY pa.RegCode ORDER BY pa.AdmitDate)

我没有机会运行查询,因此某些语法可能不正确,但我希望您对如何检索数据有所了解。

答案 1 :(得分:1)

您似乎想要这样的东西:

select p.*
from (select em.ClinicCode, pa.ConsultantID, pa.RegCode as MRN, pa.AdmissionID, pa.AdmitDate, bm.PainScoreID, pn.PainScore,
             lag(pa.AdmitDate) over (partition by pa.RegCode order by pa.AdmitDate) as prev_admitDate,
             lead(pa.AdmitDate) over (partition by pa.RegCode order by pa.AdmitDate) as next_admitDate
     from v_dbPatientAdmissions pa join
          v_dbPatientBodyMass bm
          on bm.AdmissionID = pa.AdmissionID join
          v_dbPainScores pn
          on bm.PainScoreID = pn.PainScoreID join
          v_dbEmpClinicCodes em
          on em.EmpID = pa.ConsultantID
     where pa.ConsultantID = 1108
    ) p
where p.admitdate < dateadd(hour, 24, prev_admitdate) or
      p.admitdate > dateadd(hour, -24, next_admitdate);

这假设录取是针对相同的ConsultantID。如果它们可以跨越consultantId s,那么您将需要删除where子句。