SQL Server:为结果集中的每个子组选择Max

时间:2017-04-01 08:15:00

标签: sql sql-server greatest-n-per-group

我是 SQL Server 的新手。我有一个包含用户名,地址和更新日期的表。

以下查询为我提供了该表中所有必需的详细信息,但我的问题是该表可以包含同一用户/ ID的多个记录,以防他们多次更改其地址。

我如何仅从每个用户/ ID的最新更新中获取地址?我尝试使用DISTINCTTOP1等,但无法找到实现此功能的方法。

我的查询:

SELECT
    u.ID
    , u.lastName + ', ' + u.firstName AS fullName
    , u.DOB
    , u.homeAddress
    , u.updateDate AS lastUpdate
FROM dbo.Users u
GROUP BY u.ID, u.lastName, u.firstName, u.homeAddress, u.updateDate
ORDER BY u.lastName, u.firstName, updateDate DESC

4 个答案:

答案 0 :(得分:2)

rextester demo

select * from (
select rn = row_number() over (partition by id order by updateDate desc), *
from Users
) x
where rn = 1

答案 1 :(得分:1)

或者您可以采用更直观的旧式风格,只需使用子选项:

SELECT
    u.ID
    , u.lastName + ', ' + u.firstName AS fullName
    , u.DOB
    , u.homeAddress
    , u.updateDate AS lastUpdate
FROM dbo.Users u INNER JOIN
(
    -- here is where we get the last update
    select u.ID, max(u.updateDate) as lastUpdate from dbo.Users group by u.ID
) as s
on u.ID = s.ID
-- and here we force the address of the last update
WHERE u.updateDate = s.lastUpdate 
GROUP BY u.ID, u.lastName, u.firstName, u.homeAddress, u.updateDate
ORDER BY u.lastName, u.firstName, updateDate DESC

您将获得子选择中每个ID的最后一次更新,并在WHERE子句中过滤此日期。

答案 2 :(得分:0)

使用ROW_NUMBER

SELECT * FROM (
SELECT ROW_NUMBER() OVER (PARTITION BY  u.ID ORDER BY u.updateDate DESC ) AS SNO
    , u.ID
    , u.lastName + ', ' + u.firstName AS fullName
    , u.DOB
    , u.homeAddress
    , u.updateDate AS lastUpdate
    FROM dbo.Users u
)A
WHERE A.SNO=1

答案 3 :(得分:0)

您需要(1)对您的用户ID进行分组; (2)将您的更新日期和(3) DISTINCT降序为您的用户ID,如下所示:

SELECT
    DISTINCT u.ID
    , u.lastName + ', ' + u.firstName AS fullName
    , u.DOB
    , u.homeAddress
    , u.updateDate AS lastUpdate
FROM dbo.Users u
GROUP BY u.ID
ORDER BY u.updateDate DESC