| Author |
Topic |
|
MevaD
Starting Member
32 Posts |
Posted - 2010-05-06 : 16:58:16
|
| Hello,I have a situation where I need to find the last line item from the last transaction for each invoice.Here's the setup (NOTE: I did not design the table or database):Invoice table is linked to Transaction table by CustID and TransID.-------------Invoice Table ------------- CustID InvIDInvoiceStatus -----------Trans Table-----------CustIDInvIDTransactionDateLineItemID (smallint)SAMPLE DATAInvoice1, 3, Open1, 4, Closed2, 3, Open3, 1, OpenTrans1, 3, 04-30-2010, 11, 3, 04-30-2010, 21, 3, 04-30-2010, 32, 3, 05-01-2010, 12, 3, 05-01-2010, 23, 1, 05-01-2010, 1So the query should return:1, 3, Open, 1, 3, 04-30-2010, 32, 3, Open, 2, 3, 05-01-2010, 23, 1, Open, 3, 1, 05-01-2010, 1I need to be able to link the record with the largest LineItemID AND latest TransactionDate for all 'Open' invoices in the Invoice table.The DBMS is MS-SQL 2005.Thanks for any ideas. |
|
|
vijayisonly
Master Smack Fu Yak Hacker
1836 Posts |
Posted - 2010-05-06 : 17:36:55
|
Try thisselect a.CustID,a.InvID,a.InvoiceStatus,b.TransactionDate,b.LineItemIDfrom Invoice a inner join(select row_number () over(partition by CustID,InvID order by LineItemID desc,TransactionDate desc) as seq, * from Trans) bon a.CustID = b.CustID and a.InvID = b.InvID and b.seq = 1 |
 |
|
|
MevaD
Starting Member
32 Posts |
Posted - 2010-05-06 : 17:58:22
|
| Yes!! It works. Thank you very much.I appreciate you help.-MD |
 |
|
|
vijayisonly
Master Smack Fu Yak Hacker
1836 Posts |
Posted - 2010-05-07 : 10:09:11
|
| No problem. |
 |
|
|
|
|
|