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
 General SQL Server Forums
 New to SQL Server Programming
 Need to select the last record in each group.

Author  Topic 

mikemadison
Starting Member

12 Posts

Posted - 2011-07-25 : 19:22:37
Hello:

I need to select the last record in each group of records using T-SQL.
That last record is identified by the highest value of the "Row_Number()" function which is a running number over each group.

I've tried isolating that highest value of ROWNUM with "SELECT TOP 1" and "Max()" without success. Apparently, there is no "Last()" function available in T-SQL.


SELECT Row_Number() over(Partition By col_1 ORDER BY col_2 ASC) AS ROWNUM
,col_1
,col_2
FROM MyTable


Thanks in advance for anyone offering a solution that works.

Sincerely,

Mike M.

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2011-07-25 : 20:21:56
[code]
select * from
(
SELECT
Row_Number() over(Partition By col_1 ORDER BY col_2 DESC) AS ROWNUM
,col_1
,col_2
FROM MyTable
) S
where ROWNUM = 1[/code]
Go to Top of Page

mikemadison
Starting Member

12 Posts

Posted - 2011-07-27 : 10:24:49
Thank you! You really helped me!

Mike M.
Go to Top of Page
   

- Advertisement -