有一张表格包含研究患者的日期。
select inspection_date from inspection
患者的研究不是经常随机进行的。 您希望在一行中显示第一次研究中与患者最接近的第一项研究和研究的信息。
答案 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