1

我正在使用 Select MAX 来获取最新的 [CreatedDateTime] 但是我在查询中得到重复而不是单个结果?我的 SQL 查询如下所示;

SELECT DISTINCT
i.[RecID] as AssigneeID,
t.[Owner],
t.[CreatedDateTime]
FROM Incident as i
Left Join Task as t
On i.[RecID] =  t.[ParentLink_RecID] 
WHERE
(t.[CreatedDateTime] IN (SELECT MAX(t.[CreatedDateTime])
        FROM Task as t
       GROUP BY t.[ParentLink_RecID]))
AND i.[Status] <> 'Closed'
AND t.[OwnerTeam] IS NOT NULL
Order By i.[RecID] ASC

从重复问题添加的示例数据:

AssigneeID                          CreatedDateTime
E94D6F547A73430BA75758C79D5BD8DB    28/05/2013 10:25
E94D6F547A73430BA75758C79D5BD8DB    28/05/2013 10:32
CB208EB6BCC24E1791F946F01D6AF97B    26/03/2013 15:14
CB208EB6BCC24E1791F946F01D6AF97B    16/05/2013 15:20
BE14926E300E45AD8A9A949114CE8026    29/04/2013 10:27
BE14926E300E45AD8A9A949114CE8026    01/05/2013 08:41

任何援助将不胜感激

4

2 回答 2

2

您的in子句正在选择任何CreatedDateTime值的最大值,而不仅仅是特定值的最大值 - 如果您只需要 RecID 和最新日期,请尝试: ParentLink_RecID RecID

SELECT i.[RecID] as AssigneeID, max(t.[CreatedDateTime]) CreatedDateTime
FROM Incident as i
Join Task as t On i.[RecID] =  t.[ParentLink_RecID] 
WHERE i.[Status] <> 'Closed'
  AND t.[OwnerTeam] IS NOT NULL
group by i.[RecID]
Order By i.[RecID] DESC
于 2013-06-16T16:30:05.097 回答
0

如果有多个具有相同值的记录,则可以得到CreatedDateTime。我认为以下查询是您想要的,我们只需选择具有最近创建的日期时间的一行并对其进行过滤:

SELECT DISTINCT
i.[RecID] as AssigneeID,
t.[Owner],
t.[CreatedDateTime]
FROM Incident as i
Left Join Task as t
On i.[RecID] =  t.[ParentLink_RecID] 
WHERE t.[ParentLink_RecID] = (SELECT TOP 1 t.[ParentLink_RecID]
                              FROM Task as t
                              ORDER BY t.[CreatedDateTime] DESC)
AND i.[Status] <> 'Closed'
AND t.[OwnerTeam] IS NOT NULL
Order By i.[RecID] ASC
于 2013-06-15T08:16:40.003 回答