选择每个不同外键的第二高值

Cha*_*tte 7 sql sql-server sql-server-2005

所以,我有两个表,帐户和发票,它们通过帐户表中的主键链接,即.account.key和invoice.key.

我想从每个帐户中选择account.accountnumber,invoice.invoicedate,invoice.invoiceamount作为第二个最新的发票.

有任何想法吗?

因此,要选择所有发票及其相应的帐号:

select a.accountnumber, i.invoicedate, i.invoiceamount
from account a
join invoice i on (a.key = i.key)
Run Code Online (Sandbox Code Playgroud)

并从整个发票表中选择第二个最新发票:

select MAX(invoicedate) from INVOICE i where invoicedate NOT IN (SELECT MAX(invoicedate) from i
Run Code Online (Sandbox Code Playgroud)

但是,如何从发票表中获取每个帐户的第二个最新发票以及帐户表中的帐号?

提前致谢.

pod*_*ska 6

通过使用ROW_NUMBER()窗口函数...

select accountnumber, invoicedate, invoiceamount 
from 
(
    select a.accountnumber, i.invoicedate, i.invoiceamount, 
        row_number() over (partition by a.accountnumber order by invoicedate desc) rn
    from account a 
        join invoice i on a.[key] = i.[key]
) v
where rn = 2
Run Code Online (Sandbox Code Playgroud)