如何显示同一个表中的值,差异为一年?

时间:2017-05-03 14:11:38

标签: sql

有一张表格包含研究患者的日期。

select inspection_date from inspection

患者的研究不是经常随机进行的。 您希望在一行中显示第一次研究中与患者最接近的第一项研究和研究的信息。

1 个答案:

答案 0 :(得分:1)

SELECT  patient, firstStudy, 
        (SELECT TOP 1 inspection_date, 
                    ABS(DATEDIFF(s,DATEADD(y,firstStudy,1),inspection_date)) AS diff FROM inspection
        WHERE patient=myPatientsFirstStudy.patient
        ORDER BY diff
        ) AS studyClosestAfterYear
FROM    (SELECT patient, 
                (SELECT TOP 1 inspection_date FROM inspection
                 WHERE patient=myPatientsWithStudy.patient
                 ORDER BY inspection_date
                ) AS firstStudy
        FROM (SELECT DISTINCT patient FROM inspection
             ) AS myPatientsWithStudy
        ) AS myPatientsFirstStudy