消除查询中的重复

时间:2013-12-26 22:33:39

标签: sql sql-server

我很难过。我已尽我所能删除重复但我还有一个。我认为Distinct会照顾这个,但也许admitDate也是不同的。

SELECT DISTINCT 
      p.mrn, 
  p.id, 
      v.PatientID,
      p.firstname, 
      p.lastname, 
      p.dob, 
--     s.SmokeStatus,  
--     v.VisitNo, 
--     s.VisitID,
--     v.ID,
   v.AdmitedDate

FROM
      tblPatient p 
      JOIN tblPatientVisit v ON p.id = v.PatientID
      JOIN tblPatientSmokingScreenOrder s ON v.id = s.VisitID
WHERE 
      isdate(p.DOB) = 1 
      AND CONVERT(date,p.DOB) <'12/10/2000' 
  AND isdate(v.AdmitedDate) = 1 
      AND CONVERT(date,v.AdmitedDate) > '06/16/2013 00:00' 
 -- AND s.TobaccoType IN ('Cigarettes','Cigars','Pipes')
  AND v.PatientType IN ('I', 'EO')
  AND NOT EXISTS (select null from 
                   tblPatientVisit
                   where v.PatientId = p.id
                  and v.PatientType = 'O')

    order by p.MRN


 MRN     ID   Patient ID LastN   FirstN   DOB             AdmitDate
 0015536    132 132 TINKER  BELL    04/20/1963  09/06/2013 14:47
 0015537    133 133 CHEF    RAMSEY  11/02/1974  08/30/2013 11:41
 0015537    133 133 CHEF    RAMSEY  11/02/1974  09/06/2013 14:42
 0015538    134 134 BARRY   MANILOW 06/17/1943  08/30/2013 11:51

厨师Ramsey不应该两次列出。由于我有一个独特的,我认为它只会拉出0015537中的一个。

1 个答案:

答案 0 :(得分:1)

区别于所有字段,而不仅仅是其中的几个字段。如果您注意到,其他一些列是不同的。这是解决问题的一种方法。它为每个mrn提取一个随机行,使用row_number()函数添加序号。

您也有一些日期问题。它的设置方式,可能会在日期上出现类型转换错误。解决方法是使用case语句。对日期常量使用ANSI标准日期格式也更好:

with t as (
      SELECT p.mrn, p.id, v.PatientID, p.firstname, p.lastname, p.dob, v.AdmitedDate,
             row_number() over (partition by p.mrn order by newid()) as seqnum
      FROM tblPatient p  oin
           tblPatientVisit v ON p.id = v.PatientID
           tblPatientSmokingScreenOrder s ON v.id = s.VisitID
      WHERE (case when isdate(p.DOB) = 1 then CONVERT(date, p.DOB) end) < '2000-12-10' and
            (case when isdate(v.AdmitedDate) = 1 then CONVERT(date, v.AdmitedDate) end) > '2013-06-16' and
            v.PatientType IN ('I', 'EO') and
            NOT EXISTS (select 1 from 
                        tblPatientVisit
                        where v.PatientId = p.id and v.PatientType = 'O'
                       )
    )
select t.*
from t
where seqnum = 1
order by p.MRN;