我正在使用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
任何帮助将不胜感激
答案 0 :(得分:2)
您的in
条款选择的CreatedDateTime
值是任何 ParentLink_RecID
值的最大值,而不仅仅是特定值的最大值 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
答案 1 :(得分: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