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

时间:2012-10-05 10:36:31

标签: 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)

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

select MAX(invoicedate) from INVOICE i where invoicedate NOT IN (SELECT MAX(invoicedate) from i

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

提前致谢。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:-1)

尝试使用:

select a.accountnumber, i.invoicedate, i.invoiceamount 
from account a 
join invoice i on a.[key] = i.[key]
and i.invoicedate in
(select max(invoicedate) as secondmaxdate from invoice where invoicedate not in
(select max(invoicedate) as maxdate from invoice group by [key])
group by [key])