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)
 Get records based on ID for particular name

Author  Topic 

habsql
Starting Member

1 Post

Posted - 2012-07-22 : 13:52:31
Table Structure

ID NAME DATE
1 HAB 12/10/2012 10:10:20
1 HAB 11/12/2010 10:23:33
1 JOHN 12/12/2012 10:11:10
1 SAM 12/13/2012 11:12:30
2 HAB 12/12/2010 10:13:40
2 MAS 10/15/2012 10:10:20
2 HAB 09/05/2010 10:20:40
3 RAA 12/12/2010 10:13:10

I want to fetch the record based on user with last modified
suppose if i take user named "HAB" he presents in ID(1 and 2)so from these two ID's i want only which record is Last Modified.

Expected Result to be

ID NAME DATE
1 HAB 12/10/2012 10:10:20
2 HAB 12/12/2010 10:13:40

Please help me out!!!

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-07-22 : 14:15:15
You can use one or the other of the following. If you have just these three columns in the table, the first one using the MAX function may be better. If you have additional columns that you want to bring in that correspond to the row with the max date, the second approach can be adapted to accommodate that:

-- 1
SELECT
a.ID,
a.Name,
MAX(a.Date) AS [Date]
FROM
YourTable a
GROUP BY
a.ID,
a.Name;

-- 2
SELECT
a.ID,
a.Name,
b.Date
FROM
YourTable a
CROSS APPLY
(
SELECT TOP 1 c.Date FROM YourTable c
WHERE c.Name = a.Name AND c.Id = a.Id
ORDER BY c.Date DESC
) b;
Go to Top of Page
   

- Advertisement -