NinjaCat NinjaCat - 1 month ago 4
SQL Question

Select DISTINCT, return entire row

I have a table with 10 columns.
I want to return all rows for which Col006 is distinct, but return all columns...

How can I do this?

if column 6 appears like this:

| Column 6 |
| item1 |
| item1 |
| item2 |
| item1 |


I want to return two rows, one of the records with item1 and the other with item2, along with all other columns.

Answer

In SQL Server 2005 and above:

;WITH    q AS
        (
        SELECT  *, ROW_NUMBER() OVER (PARTITION BY col6 ORDER BY id) rn
        FROM    mytable
        )
SELECT  *
FROM    q
WHERE   rn = 1

In SQL Server 2000, provided that you have a primary key column:

SELECT  mt.*
FROM    (
        SELECT  DISTINCT col6
        FROM    mytable
        ) mto
JOIN    mytable mt
ON      mt.id = 
        (
        SELECT  TOP 1 id
        FROM    mytable mti
        WHERE   mti.col6 = mto.col6
        -- ORDER BY
        --      id
        --  Uncomment the lines above if the order matters
        )

Update:

Check your database version and compatibility level:

SELECT  @@VERSION

SELECT  COMPATIBILITY_LEVEL
FROM    sys.databases
WHERE   name = DB_NAME()
Comments