获取查询中的最大开始日期

时间:2016-07-18 08:07:24

标签: sql date group-by max

我想在查询中获取最新日期以避免重复。

   (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中看到最新的日期。有什么想法吗?

1 个答案:

答案 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