在特定时间范围内查找所有DATEDIFF

时间:2012-08-06 15:16:01

标签: sql sql-server-2008

我有一张像enter image description here

这样的表格

使用patientid, admissiondate, dischargedate的复合键。

请注意,patientID 6的{​​{1}}为10/21,dischargedate为10/22。

同样admissiondate的{​​{1}}为2/20,patientID 11为6/14。

dischargedate可以在数据库中的次数没有限制。

如何获取admissiondate比之前patientID大3天或更少天的所有实例的列表? (admissiondate符合此法案)。多次自我加入是不对的。我有

dischargedate

获取不止一次见过的所有人的列表。如何patientid 6确保select patientid, p.admissiondate, p.dischargedate from Patient as p where patientid in ( select patientid from Patient p2 group by patientid having count(*) > 1 ) order by patientid, admissiondate admissionDate之后的三天内? (来自此示例中的上一行)。

我不能做一个简单的dischargedate,因为我不担心任何一次访问datediff(dd,admissiondate, dischargedate),只是因为NEXT datediff在前一天的三天之内到来{ {1}}

1 个答案:

答案 0 :(得分:4)

;with cte as
(
     -- get admission dates by patient in order
select *, ROW_NUMBER() over (partition by PatientID order by AdmissionDate) as AdOrd 
from patient
)
     -- find the gaps between adjacent admissions
    select admissions.patientid, discharges.dischargedate, admissions.admissiondate     
    from cte admissions
        inner join cte discharges on discharges.patientid=admissions.patientid
            and discharges.AdOrd = admissions.AdOrd-1
    where DATEDIFF(D,discharges.dischargedate,admissions.admissiondate )<=3