tags:

views:

59

answers:

3

I have a SQL Server 2008 database with records like the following

001 CAT 1 2 3 
002 DOG 3 3 1
003 DOG 2 1 1
004 DOG 2 1 3
005 CAT 1 3 4

I want to take 1 row for each unique value in column 2 (cat and dog)

so this would get me (one possible answer):

001 CAT 1 2 3
002 DOG 3 3 1

Column 1 is the PK and is a string. Column 2 is a string

Columns 3-5 are just there to indicate there are other variable fields which I need in the final result.

A: 
SELECT pk, DISTINCT pet, col3, col4, col5 FROM myPetsTable

Would that work? Taking a shot in the dark here :)

inkedmn
Nope, it would bomb on the distinct. The order matters.
Dr. Zim
As far as I know thats not valid SQL
sylvanaar
Dr. Zim is correct - `DISTINCT` is applied to all columns in the `SELECT` clause, not selectively.
OMG Ponies
Fair enough - as I said, it was a guess :)
inkedmn
+5  A: 
SELECT t1.* 
FROM YourTable t1
    JOIN 
    (SELECT MIN(Col1) AS FirstId 
     FROM YourTable GROUP BY Col2) x ON t1.Col1 = x.FirstId
AdaTheDev
This is really close to what I was trying - except yours is correct.
sylvanaar
+1, I was thinking ROW_NUMBER, but this is better
KM
A: 

how do you determine which row is returned? Do you really not care about the other columns?

Nathan DeWitt
i just want any 1 of the rows - i don't care which
sylvanaar