Here is a simplified transactions table.
Each row is a transaction that has a unique transac id (identity field if you will), an accountpointer (foreign key to the accounts table which is not displayed here), a transac date and a dollar amount.
Sample data below:
trans_id acc_ptr trans_date amount
1 12 2011-08-24 2.0
2 12 2011-08-25 3.0
3 14 2011-07-28 -3.0
4 16 2011-06-14 -1.0
5 12 2011-05-15 0.5
6 16 2011-07-30 -2
What I want is very simple. Display the most recent transac grouped by acc_ptr including the amount for that date.
What I have works perfectly, but what I would like to know is, is there a more elegant way (as far as programming goes) or more efficient way of dealing with this problem, specifically my treatment of the subquery for amount? Would like to see how you would approach it.
My approach:
select acc_ptr
, max(trans_date) as [most rec transac date]
, (select amount from transactions t2
where t2.trans_date = max(t1.trans_date)
and t2.acc_ptr = t1.acc_ptr) as amount
from transactions t1
group by acc_ptr
The first alternative that comes to mind is to use analytics (IE: ROW_NUMBER), but that’s SQL Server 2005+ functionality.
There’s no performance value in this example to using a CTE (
WITHsyntax) – this is equivalent: