Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select DISTINCT, return entire row

Tags:

sql

sql-server

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.

like image 847
NinjaCat Avatar asked Aug 19 '10 07:08

NinjaCat


People also ask

How do I SELECT distinct rows in SQL?

If the ALL keyword is specified, the query does not eliminate duplicate rows. This is the default behavior if neither ALL nor DISTINCT is specified. If the DISTINCT keyword is specified, a query eliminates rows that are duplicates according to the columns in the SELECT clause.

What does SELECT distinct return?

The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.

Does distinct return the first row?

It neither returns "the first row" nor the "last row". It returns the distinct values of the name column. It doesn't matter to which row they belong.


1 Answers

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()
like image 83
Quassnoi Avatar answered Nov 02 '22 19:11

Quassnoi