从具有多个出现次数的表中获取唯一记录

时间:2017-04-19 20:11:58

标签: sql

我试图提取所有患者记录(没有重复)。在我的数据库中,所有患者都有多个访问ID和多个访问日期。

我试过这个:

SELECT DISTINCT *
FROM PatientVisit
WHERE Visit IN (SELECT MIN(Visit) FROM  PatientVisit GROUP BY PatientProfileId)

1 个答案:

答案 0 :(得分:0)

试试这个。

    SELECT 
    DISTINCT VisitMain.PatientID
    ,MaxVisit.FirstVisit
    ,MinVisit.LastVisit
FROM
    PatientVisit VisitMain (NOLOCK)
LEFT JOIN
    (SELECT 
        PatientID,FirstVisit = MAX(CONVERT(DATETIME,Visit))
     FROM 
        PatientVisit (NOLOCK)
     GROUP BY
        PatientID) MaxVisit
ON VisitMain.PatientID = MaxVisit.PatientID
LEFT JOIN
    (SELECT 
        PatientID,LastVisit = MIN(CONVERT(DATETIME,Visit))
     FROM 
        PatientVisit (NOLOCK)
     GROUP BY
        PatientID) MinVisit
ON VisitMain.PatientID = MinVisit.PatientID