SQL - Return 当第 1 列有多个条目时,第 1 列和第 2 列的最大值

SQL - Return column1 and max of column2 when column 1 has multiple entries

我有一个 table,其中包含帐号和日期(在其他列中)。对于每个帐号,都有多个具有不同日期的条目。我只想 return 具有最近日期的行和我从其他来源获得的帐号。

这是我尝试过的方法,但我明白为什么这不起作用。我只是想不出替代方法。

SELECT ACCOUNT_NUMBER, MAX(DATE) FROM PORTFOLIO
WHERE ACCOUNT_NUMBER IN (444347, 899999,
887111,
220922)
GROUP BY ACCOUNT_NUMBER 

I want to return only the row with the most recent date and only account numbers that I have from another source.

我了解到您想要每个帐号的最新记录。如果是这样,一种解决方案是使用解析函数:

select *
from (
    select
        p.*,
        rank() over(partition by account_number order by date desc) rn
    from portfolio p
    where account_number in (444347, 899999, 887111, 220922)
) t
where rn = 1

另一种方法使用相关子查询进行过滤:

select p.*
from portfolio p
where 
    p.account_number in (444347, 899999, 887111, 220922)    
    and p.date = (
        select max(p1.date) from portfolio p1 where p1.account_number = p.account_number
    )
SELECT ACCOUNT_NUMBER, DATE
FROM PORTFOLIO
WHERE ACCOUNT_NUMBER IN (444347, 899999, 887111, 220922)
    and date = (select max(date) from portfolio b where portfolio.account_number = account_number)