2012-10-05 17 views
7

Quindi, ho due tabelle, un conto e una fattura, sono collegati dalla chiave primaria dalla tabella dell'account, ad esempio. account.key e fattura.key.Seleziona il secondo valore più alto per chiave esterna distinta

Desidero selezionare account.accountnumber, fattoice.invoicedate, fattoice.invoiceamount per la seconda più recente fatturata da ciascun account.

Qualche idea?

Quindi, per selezionare tutte le fatture e le loro corrispondenti numeri di conto:

select a.accountnumber, i.invoicedate, i.invoiceamount 
from account a 
join invoice i on (a.key = i.key) 

e per selezionare la seconda ultima fattura l'intera tabella fattura:

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

Ma come faccio a ottenere il secondo più recente fattura, per account dalla tabella delle fatture, insieme al numero di conto dalla tabella dell'account?

Grazie in anticipo.

risposta

6

Utilizzando la funzione ROW_NUMBER() finestre ...

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

provare a utilizzare questo:

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

Non solo questo è più di contorto, non funzionerà se le date delle fatture di condivisione. – podiluska

Problemi correlati