First, I assume you mean "top rows when ordered by a certain field", like date. You obviously need some way to designate the "top" rows.I'll assume you want the largest 3 invoices per client:This gives the ranking of each invoice per client:SELECT clientID, InvoiceNumber, InvoiceDate, InvoiceAmt, (SELECT COUNT(*) FROM Invoices WHERE ClientID = I.ClientID AND InvoiceAmount <= I.InvoiceAmount) as RankFROM Invoices I
We just do a query of the above, and we are good to go:SELECT * FROM (above SQL) AWHERE Rank <= 5ORDER BY ClientID, Rank
Note that if there is a tie, potentially more than 5 rows will be returned for each clientID. You will need a rule if you wish for no more than 5 to ever be returned. YOu need to logically make a rule, let's say: if there is a tie, than the invoice with the earliest date ranks first.If so, then the first SQL statement becomes:SELECT clientID, InvoiceNumber, InvoiceAmt, (SELECT COUNT(*) FROM Invoices WHERE ClientID = I.ClientID AND (InvoiceAmount <= I.InvoiceAmount) OR (InvoiceAmount = I.INvoiceAmount AND InvoiceDate <= I.InvoiceDate)) as RankFROM Invoices I
I hope this leads you down the right trail. This can be tricky but you can learn a whole bunch of new techniques ....- Jeff