如何按最大日期删除重复项

时间:2017-01-23 20:25:00

标签: sql tsql sql-server-2005

我有患者身份证,同意是或否,以及同意日期。可能有多个同意日期,我只想要与最近同意日期相关的同意书。在下面的查询中,我遇到了将Group By子句放在何处以及一些无效列名的问题。

select CASE_NUM
      ,max(replace(replace(replace(
                convert(varchar(10),convert(datetime,TRCLPLAN.[DATE],112),126)
            ,'-',''),'T',''),':','')
          ) as CONSENT_DATE
      ,case
           when PHOTO_OK = 1
               then 'Y'
           when PHOTO_OK = 2
               then 'N'
           when PHOTO_OK is null
               then 'U'
       end as CONSENT
from
     (select CASE_NUM
            ,max(replace(replace(replace(
                    convert(varchar(10),convert(datetime,TRCLPLAN.[DATE],112),126)
                  ,'-',''),'T',''),':','')
                ) as CONSENT_DATE
            ,case
                 when PHOTO_OK = 1
                     then 'Y'
                 when PHOTO_OK = 2
                     then 'N'
                 when PHOTO_OK is null
                     then 'U'
             end as CONSENT
            ,row_number() over(partition by CASE_NUM order by TRCLPLAN.[DATE] desc) as rn
      from
           CDCLIENT
          inner join TRCLQSC8
              on CDCLIENT.ID = TRCLQSC8.CLIENT_ID
          inner join TRCLPLAN
              on TRCLQSC8.TRT_PLAN_ID = TRCLPLAN.ID
          inner join TRCLQDS3
              on TRCLQSC8.TRT_PLAN_ID = TRCLQDS3.TRT_PLAN_ID
     ) as derivedTable
where derivedTable.rn = 1
--GROUP BY CASE_NUM
--        ,CONSENT

0 个答案:

没有答案