我想在查询中获取最新日期以避免重复。
(SELECT DISTINCT
Person.Snapshot.[Person Number] AS UserKey,
Person.Snapshot.[Unique Name],
Person.Snapshot.Surname,
Person.Snapshot.[First Name], ' ' AS MiddleName,
' ' AS DateOfBirth,
Person.Images.Photo AS PictureName,
CardActivationDate = MAX(Person.Snapshot.[Start Date]),
Person.Snapshot.[Unit Name] AS AccessGroup
FROM Person.Snapshot INNER JOIN Person.Images ON Person.Images.[Person Number] = Person.Snapshot.[Person Number]
GROUP BY Person.Snapshot.[Person Number], Person.Snapshot.[Unique Name],
Person.Snapshot.Surname, Person.Snapshot.[First Name],
Person.Images.Photo,
Person.Snapshot.[Unit Name])
O / P:
5622 Adams, Janet 5622 Adams Janet Science & Technology 2002-08-01
5622 Adams, Janet 5622 Adams Janet Social & Sciences 2006-08-01
5623 Anstey, Diane 5623 Anstey Diane Science & Technology 2003-09-01
5623 Anstey, Diane 5623 Anstey Diane Social & Sciences 2006-08-01
5623 Anstey, Diane 5623 Anstey Diane Social Studies 2005-02-01
我想在上面的SQL中看到最新的日期。有什么想法吗?
答案 0 :(得分:1)
尝试将ROW_NUMBER()
用于SQLSERVER
;WITH CTE
AS
(
SELECT
Person.Snapshot.[Person Number] AS UserKey,
Person.Snapshot.[Unique Name],
Person.Snapshot.Surname,
Person.Snapshot.[First Name], ' ' AS MiddleName,
' ' AS DateOfBirth,
Person.Images.Photo AS PictureName,
Person.Snapshot.[Start Date],
Person.Snapshot.[Unit Name] AS AccessGroupm,
ROW_NUMBER() OVER (PARTITION BY Person.Snapshot.[Person Number], Person.Snapshot.[Unique Name],
Person.Snapshot.Surname, Person.Snapshot.[First Name],
Person.Images.Photo,
Person.Snapshot.[Unit Name] ORDER BY (Person.Snapshot.[Start Date] DESC) AS RN
FROM
person.Snapshot PS
INNER JOIN
Person.Images PI ON Person.Images.[Person Number] = Person.Snapshot.[Person Number]
)
SELECT * FROM CTE WHERE RN=1