我有一个包含文档ID列和日期列的视图以及与此问题无关的十几个其他列。可以有多个具有相同文档ID的行,但日期通常不同。这表示它是同一个文档,只是它的修订版。问题是如果我有两行文档ID和日期是相同的,我得到两个。我只想得到一个。无论哪一个,只要我得到一个。
以下内容与文档ID和日期相同有重复。
SELECT FSD.*
FROM vFSD FSD
INNER JOIN
(
SELECT InternalID, MAX(FileLastUploadedDate) AS FileLastUploadedDate
FROM vFSD
GROUP BY InternalID
) gFSD ON FSD.InternalID = gFSD.InternalID AND FSD.FileLastUploadedDate = gFSD.FileLastUploadedDate
我也尝试过DISTINCT,但它没有解决问题。
SELECT DISTINCT FSD.*
FROM vFSD FSD
INNER JOIN
(
SELECT DISTINCT InternalID, MAX(FileLastUploadedDate) AS FileLastUploadedDate
FROM vFSD
GROUP BY InternalID
) gFSD ON FSD.InternalID = gFSD.InternalID AND FSD.FileLastUploadedDate = gFSD.FileLastUploadedDate
答案 0 :(得分:4)
您可以使用ROW_NUMBER
仅在两个与FileLastUploadedDate
InternalID
绑定的情况下带回一个任意行
WITH CTE
AS (SELECT *,
ROW_NUMBER() OVER (PARTITION BY InternalID
ORDER BY FileLastUploadedDate DESC) AS RN
FROM vFSD)
SELECT InternalID,
FileLastUploadedDate
/*Other desired columns*/
FROM CTE
WHERE RN = 1