SQL 服务器:Select 结果集中每个子组的最大值

SQL Server: Select Max for each sub group in result set

我是 SQL 服务器 的新手。我有一个包含用户名、地址和更新日期的 table。

以下查询为我提供了 table 的所有必需详细信息,但我的问题是 table 可以包含同一用户/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

选择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

您需要(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

rextester demo

select * from (
select rn = row_number() over (partition by id order by updateDate desc), *
from Users
) x
where rn = 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 子句中过滤此日期。