在不使用Distinct函数的情况下删除SQL中的重复项

时间:2017-04-27 15:32:24

标签: sql sql-server

我可能在这个

上遗漏了一些简单的东西
SELECT distinct
A.ClaimNumber, 
C.ActivityDetail, 
C.CreatedDateTime AS DateClosed, 
A.CreatedDate as OpenDate, 
DATEDIFF(DAY,CONVERT(DATE,A.CreatedDate),CONVERT(DATE,C.CreatedDateTime)) AS 'Days until closed'
FROM
    ASR.dbo.tblRepairRequestActivityStream C
    JOIN ASR.dbo.tblClaimReason A
    ON  
        A.ClaimNumber = C.ClaimNumber

WHERE
    C.ActivityDetail = 'FROM Ready_For_Pickup TO Closed'
    AND C.CreatedDateTime > '2017-04-16'
    and a.Item not like 'emms'
    and a.Item not like 'detl' 
    and a.item not like 'wind'
GROUP BY
    A.ClaimNumber, C.ActivityDetail, C.CreatedDateTime, A.CreatedDate, a.Item
ORDER BY 
    C.CreatedDateTime

我仍然在索赔号上得到重复,我相信这张票可能会重新开启并再次关闭。我该如何删除重复项?

1 个答案:

答案 0 :(得分:3)

您可以使用:source $MYVIMRC和/或min()作为日期:

max()

此外,select A.ClaimNumber , C.ActivityDetail , max(C.CreatedDateTime) as DateClosed , min(A.CreatedDate) as OpenDate , datediff(day, convert(date,min(A.CreatedDate)), convert(date, max(C.CreatedDateTime)) as [Days until closed] from asr.dbo.tblRepairRequestActivityStream C inner join asr.dbo.tblClaimReason A on A.ClaimNumber = C.ClaimNumber where C.ActivityDetail = 'from Ready_For_Pickup to Closed' and C.CreatedDateTime > '2017-04-16' and a.Item not like 'emms' and a.Item not like 'detl' and a.item not like 'wind' group by A.ClaimNumber , C.ActivityDetail --, C.CreatedDateTime --, A.CreatedDate --, a.Item /* not in select */ order by max(C.CreatedDateTime) 位于您的a.Item但不在您的group by中,这可能导致了其他重复。

使用 top with ties

row_number()

select

使用Common Table Expression row_number() 版本:

select top 1 with ties
    A.ClaimNumber
  , C.ActivityDetail
  , C.CreatedDateTime as DateClosed
  , A.CreatedDate as OpenDate
  , datediff(day, convert(date,A.CreatedDate), convert(date, C.CreatedDateTime)) as [Days until closed]
from asr.dbo.tblRepairRequestActivityStream C
  inner join asr.dbo.tblClaimReason A 
    on A.ClaimNumber = C.ClaimNumber
where C.ActivityDetail = 'from Ready_For_Pickup to Closed' 
  and C.CreatedDateTime > '2017-04-16'
  and a.Item not in ('emms','detl','wind')
order by row_number() over (
  partition by A.ClaimNumber 
  order by c.CreatedDatetime desc /* most recent */
         , a.CreatedDate desc     /* most recent */
  )