Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Selecting Last Transaction Using Row() feature

Author  Topic 

omega1983
Starting Member

40 Posts

Posted - 2010-08-20 : 10:26:43
begin try drop table #Last end try begin catch end catch

select giftid,giftjntamt,gifteffdat,ROW_NUMBER()
OVER(PARTITION BY giftid ORDER BY gifteffdat)as col
into #Last
from gifts with(nolock)
where gifteffdat >='7/1/1984'
and giftacctdv = '11'
and gifttype in ('c','g','y')
group by giftid,giftjntamt,gifteffdat
order by giftid

sample data
giftid giftjntamt gifteffdat col
0000000014 500.00 2004-06-02 00:00:00.000 1
0000000014 2000.00 2005-08-09 00:00:00.000 2
0000000014 1000.00 2007-04-09 00:00:00.000 3 (desired)
0000000081 250.00 2002-03-12 00:00:00.000 1(desired)
0000000147 30.00 2006-04-05 00:00:00.000 1(desired)
0000000270 1000.00 1995-10-05 00:00:00.000 1
0000000270 10.00 2008-02-22 00:00:00.000 2(desired)
Desired output
0000000014 1000.00 2007-04-09 00:00:00.000
0000000081 250.00 2002-03-12 00:00:00.000
0000000147 30.00 2006-04-05 00:00:00.000
0000000270 10.00 2008-02-22 00:00:00.000

Essentially I want the last row for each giftid because it represents the most recent transaction. Thus I want the last giftid, last giftamount and last giftdate.
Using the row feature how would I accomplish this

vijayisonly
Master Smack Fu Yak Hacker

1836 Posts

Posted - 2010-08-20 : 10:48:35
[code]select giftid,giftjntamt,gifteffdat from
(
select giftid,giftjntamt,gifteffdat,ROW_NUMBER()
OVER(PARTITION BY giftid ORDER BY gifteffdat DESC)as seq
from gifts
where gifteffdat >= '19840701'
and giftacctdv = '11'
and gifttype in ('c','g','y')
) t
where t.seq = 1[/code]
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-08-20 : 11:15:34
see scenario 2

http://visakhm.blogspot.com/2010/01/multipurpose-apply-operator.html

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -