Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Distinct with multiple column values?

Status
Not open for further replies.

twifosp

Programmer
Jul 25, 2003
186
0
0
US
I'm trying to get a list of distinct values.

Lets say I have a list of ids.

1
2
3
4

Those ids have other info, specifically timestamps. So if I have multiple events on one of the id, then it gets another timestamp. So what I end up is something like this:

Id timestamp
1 3:04 pm
2 5:03 pm
2 5:05 pm
3 6:00 pm
3 6:30 pm
4 7:00 pm

So how would I go about doing a select distinct(id) where it only grabs the first one?
 
Select ID, Min(TimeStamp) From myTable Group By ID
 
Thank you for the reply... my fault for not specifying that I have additional values that won't be contained in an aggregate function.

I have 11 columns that I have to select...
 
Try It:

Select * From myTable
Where TimeStamp In
(Select Min(TimeStamp) From myTable Group By ID)
 
Ahh, why didn't I think of using an in subquery... well thats why I love this forum, always someone who thinks of what you didn't.

Thanks David!
 
That query isn't necessarily going to work properly. What happens if one id has a timestamp that happens to match the MIN(timestamp) of another id? That row will get included wrongly. You need to correlate the subquery like this:

Code:
SELECT * FROM mytable t
WHERE timestamp = (
  SELECT MIN(timestamp)
  FROM mytable
  WHERE id = t.id
)

--James
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top