Advertisement

04.04.2008 at 02:52PM PDT, ID: 23297549
[x]
Attachment Details

How to select the newest date for each unique value in a table?

Asked by tds_softwaredev in MS SQL Server, SQL Query Syntax, SQL Server 2005

Tags: SQL, SQL Server 2005

I would like to create a query that looks through a table, and for each unique key in one field, find the newest corresponding date located in another field.

If I have a table such as:

tblAppointment
-----------------------------
ID|Name| Date
-----------------------
1 | ptn1 | 3/5/2008
2 | ptn1 | 1/8/2007
3 | ptn2 | 1/2/2006
4 | ptn2 | 2/5/2008
5 | ptn3 | 3/7/2008
6 | ptn3 | 2/5/2009

Is there a query that will return:

ID|Name| Date
1 | ptn1 | 3/5/2008
4 | ptn2 | 2/5/2008
6 | ptn3 | 2/5/2009

One way I was thinking, which doesn't work, would be something like:

SELECT DISTINCT ID, Name, Date FROM (SELECT * FROM tblAppointment ORDER BY Date) as SortedTable

The idea was to get a subquery with all the dates sorted, then do a distinct, hoping that the distinct would go in order of the ordered table, so it would choose the newest dates for each Name. Of course this doesn't work, but thats kind of the idea behind what I want.Start Free Trial
[+][-]04.04.2008 at 02:58PM PDT, ID: 21285930

View this solution now by starting your 7-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

 

About this solution

Zones: MS SQL Server, SQL Query Syntax, SQL Server 2005
Tags: SQL, SQL Server 2005
Sign Up Now!
Solution Provided By: aneeshattingal
Participating Experts: 1
Solution Grade: A
 
 
 
Loading Advertisement...
20080716-EE-VQP-32 / EE_QW_2_20070628