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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problems with Distinct

Status
Not open for further replies.

lumstar

Technical User
Jan 29, 2002
177
CA
I have the following:
Code:
ID    Name
-----------
1     Bob
2     Jimmy
3     Cheryl
1     Susan
3     Michael

I want to select only one Name for each of the distinct ID Values. The following is what I want:
Code:
ID    Name
-----------
1     Bob
2     Jimmy
3     Cheryl
Or something similar.

I have tried "SELECT DISTINCT ID, Name from Table" but it is not working for me, I don't think Group By applies because I am not using aggregate functions. What should I do?

Thanks,
Lumstar
 
How do you Know that the return for ID 3 should be cheryl and not Michael? are you after just the first name that is associated with an ID?

Shoot Me! Shoot Me NOW!!!
- Daffy Duck
 
I don't care which tuple gets selected, so long as there is only one for each ID. Thanks.

Lumstar
______________________________________
And The Star Continues To Shine....
 
I do not see a straight forward method to get this but here are a couple of options you can pursue:

1) Create an Identity column on the table and use min(Identity Column) to get a single tuple per ID.

2) Use something like min(len(name)) to get only one value per ID. The problem with using this approach is that you might get more than one entry per ID if the length of both the names for a given ID are same.

Regards,
AA
 
Group by is exactly waht you want.

Select min(Name) from Table Group By ID

This will get you the first name alphabetically for each id.


Questions about posting. See faq183-874
Click here to learn Ways to help with Tsunami Relief
 
I also want to select the ID though. I tried:
Code:
SELECT ID, Name FROM Table GROUP BY ID

It returns a sql error.

How would I do this?

TIA

Lumstar
______________________________________
And The Star Continues To Shine....
 
Good point sqlsister! I overlooked the fact that lumstar's requirement id not have a preference of one row over other.

Regards,
AA
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top