使用SQL,当有多个具有相同最大值时,如何选择最大值?

问题描述 投票:0回答:1

我正在尝试为每个人选择最大导入日期。对于“Bob James”这个人,他应该选择 ID 为 267311 和 267342 的最后 2 行。我需要查看表中的每一列,但只查看最大导入日期行或行(如果它们有多个文件进入)同一日期。 我尝试创建子查询并将其绑定回一个更大的查询,但是当我尝试使用 max 时,它仅带回导入日期为 11-01-2024 的一行。

select MAX(importdate),
firstname, lastname 
from ClmEligibility_Intake 
where lastname = 'james'
and firstname = 'bob'
group by firstname, lastname

enter image description here

也尝试了这个子查询,但不起作用。它应该只带回 2 个 ID:

enter image description here

sql subquery max aggregate sql-function
1个回答
0
投票

简单方法:

--get all the may(importdate)s per person in a CTE
;with CTE as (
    select maxdate = MAX(importdate)
        , firstname
        , lastname 
    from ClmEligibility_Intake
    group by firstname, lastname
)
--just select all the rows that have the same importdate as max(importdate)
select *
from ClmEligibility_Intake EI
    inner join CTE on CTE.lastname = EI.lastname
                  and CTE.firstname = EI.firstname
                  and CTE.maxdate = importdate

更好的方法:

select *
from ClmEligibility_Intake EI
    --self-join rows where a greater importdate exists:
    left join ClmEligibility_Intake X on X.lastname = EI.lastname
                                     and X.firstname = EI.firstname
                                     and X.importdate > EI.importdate 
where X.Id is null --only show rows for which no greater importdate was found

同样的事情,但你可能会发现这更惯用:

select *
from ClmEligibility_Intake EI
where not exists (select *
                  from ClmEligibility_Intake X
                  where X.lastname = EI.lastname
                    and X.firstname = EI.firstname
                    and X.importdate > EI.importdate)

我将表别名称为

X
,以表明它只是被拉入并被丢弃。

© www.soinside.com 2019 - 2024. All rights reserved.