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 2008 Forums
 Transact-SQL (2008)
 Finding the last record

Author  Topic 

mikemadison
Starting Member

12 Posts

Posted - 2011-07-20 : 12:45:04
Hi,

Is there a function in T-SQL that will find the last record in each group of records?

Apparently, the Last() function is only available in SQL, which is used in MS Access.

I have alternately tried to be creative in the use of the MAX() function in T-SQL.

Unfortunately, I am unable to effectively use it, due to many group-bys and joins.

Thanks in advance for any suggestions.

Mike

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2011-07-20 : 12:59:45
select top 1 <columns> from ... where... ORDER BY <whatever determines your sequence> desc

if you want that for many groups in one statement then you can place that statement in a CROSS APPLY derived table correlating the (group) with your main query.

Be One with the Optimizer
TG
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-07-21 : 02:18:17
Actually there's no concept of first and last in sql table. so you would have to specify the order in which you want to arrange records so as to get your last record. Thats why you see the ORDER BY clause in above query. if you're using TOP without ORDER BY order is not guaranteed and you might end up getting random records

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

Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2011-07-21 : 07:36:22
Do not confuse with MS ACCESS. Until you use order by clause, you can not get them

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -