sql - 查询,它提取所有记录,但只提取重复的最新记录

时间:2014-05-05 17:59:21

标签: sql sql-server

我需要哪些查询来提取所有记录,但只提取重复的最新记录?

我有重复记录的查询:

    $SELECT DISTINCT * 
FROM ['Duplicate Data$'] t1
WHERE Name in
(
    SELECT Name
    FROM ['Duplicate Data$']
    GROUP BY Name
    HAVING COUNT(*)>1
)
ORDER BY Name$      

这是最近的记录:

$SELECT DISTINCT *
FROM  ['Duplicate Data$'] t1
WHERE Date = (SELECT max(Date) FROM ['Duplicate Data$'] WHERE t1.Name =['Duplicate Data$'].Name)
ORDER BY Date DESC$                 

1 个答案:

答案 0 :(得分:2)

SELECT DISTINCT T1.* 
FROM ['Duplicate Data$'] t1
JOIN (
  SELECT Name, MAX(DATE) AS [MaxDate]
  FROM ['Duplicate Data$']
  GROUP BY Name
  HAVING COUNT(*)>1
) AS D
ON D.Name = T1.Name 
AND D.MaxDate = T1.Date
ORDER BY T1.Name