2012-10-05 26 views
7

所以,我有兩個表,帳戶和發票,它們通過帳戶表中的主鍵即鏈接。 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 

但如何獲取第二最新發票,發票表中的每個帳戶以及帳戶表中的帳戶號碼?

在此先感謝。

回答

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

嘗試使用這樣的:

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]) 
+0

這不僅是在錯綜複雜的,它不會工作,如果發票日期的份額。 – podiluska

相關問題