查询以获取最早的记录

时间:2017-05-31 06:43:35

标签: sql-server sql-server-2014

我有以下代码:

;with cte as (
   Select RegardingObjectId , 
          DATEADD(mi, DATEDIFF(mi, getutcdate(), getdate()),CreatedON) as [Time First Response] 
          from dbo.Email
    where DirectionCode = '1'
)
SELECT  dbo.Incident.new_CaseID as [CASE ID], 
        cte.RegardingObjectId, 
        dbo.Incident.IncidentId, 
        dbo.Incident.Title as [SUBJECT], 
        dbo.Incident.StatusCode as [STATUS], 
        cte.[Time First Response] 
from dbo.Incident
left Join cte on cte.RegardingObjectId = dbo.Incident.IncidentId
order by dbo.Incident.new_CaseID desc

此查询将返回如下结果: Images

如您所见,查询返回具有相同CASE ID的多个记录。我想要的是,对于每个多个记录具有相同的CASE ID,只检索一个具有最早[时间优先响应]的记录

2 个答案:

答案 0 :(得分:2)

您可以将查询包装在另一个CTE中,然后使用ROW_NUMBER按照[CASE ID]优先排序并获取最早的记录:

;with cte as (
   Select RegardingObjectId , 
          DATEADD(mi, DATEDIFF(mi, getutcdate(), getdate()),CreatedON) 
             as [Time First Response] 
          from dbo.Email
    where DirectionCode = '1'
), cte2 as (
   SELECT  dbo.Incident.new_CaseID as [CASE ID], 
           cte.RegardingObjectId, 
           dbo.Incident.IncidentId, 
           dbo.Incident.Title as [SUBJECT], 
           dbo.Incident.StatusCode as [STATUS], 
           cte.[Time First Response],
           ROW_NUMBER() OVER (PARTITION BY dbo.Incident.new_CaseID
                              ORDER BY cte.[Time First Response]) AS rn
   from dbo.Incident
   left Join cte on cte.RegardingObjectId = dbo.Incident.IncidentId
)
SELECT [CASE ID],
       RegardingObjectId,
       IncidentId,
       [SUBJECT], 
       [STATUS], 
       [Time First Response]
FROM cte2
WHERE rn = 1
ORDER BY [CASE ID] desc

答案 1 :(得分:0)

您可以尝试使用MIN功能

;with cte as (
   Select RegardingObjectId , 
          DATEADD(mi, DATEDIFF(mi, getutcdate(), getdate()),CreatedON) as [Time First Response] 
          from dbo.Email
    where DirectionCode = '1'
)
SELECT  dbo.Incident.new_CaseID as [CASE ID], 
        cte.RegardingObjectId, 
        dbo.Incident.IncidentId, 
        dbo.Incident.Title as [SUBJECT], 
        dbo.Incident.StatusCode as [STATUS], 
        cte.[Time First Response] 
from dbo.Incident
left Join cte on cte.RegardingObjectId = dbo.Incident.IncidentId
AND cte.[Time First Response] IN (SELECT MIN(cte.[Time First Response]) 
FROM cte WHERE cte.RegardingObjectId = dbo.Incident.IncidentId)
order by dbo.Incident.new_CaseID desc