Search code examples
sqlsql-servert-sqldistinctgroup-concat

SQL Server: How do I return all columns where one is not repeated?


I've got a table with repeating IDs which I will fix later. Basically I want to return all the rows where the ID is distinct, but I want the ENTIRE row. Something like:

select * from table group by ID

select * from table where (ID is not repeated)

In this case, they are identical rows, so I don't care if it's First or Last, Min or Max.

Note that I DON"T want to do this:

select MIN(col1), MIN(col2), ... from table group by ID

I want a way to get this result without enumerating every column.

Edit: I'm using SQL Server 2008 R2.


Solution

  • If you are using MySql, do this:

    select 
        *
    from tbl
    group by ID
    

    MySQL live test: http://www.sqlfiddle.com/#!2/8c7fd/2

    If you are using Postgresql, do this:

    select distinct on(id)
        *
    from tbl
    order by id
    

    If you want Postgresql DISTINCT ON be at least as predictable as CTE windowing function. Sort another column:

    select distinct on(id)
        *
    from tbl
    order by id
       , someColumnHere -- Choose ASC for first row, DESC for last row
    

    Postgresql live test: http://www.sqlfiddle.com/#!1/8c7fd/1

    If you are using CTE windowing-capable database (e.g. Postgres, Oracle, Sql Server), use this:

    with ranked as
    (
      select 
          rank() over(partition by id order by column) rn,
          *
      from tbl
    )
    select * from ranked where rn = 1
    

    CTE windowing-capable databases:

    Posgtresql: http://www.sqlfiddle.com/#!1/8c7fd/2

    Oracle: http://www.sqlfiddle.com/#!4/b5cf9/1

    Sql Server: http://www.sqlfiddle.com/#!3/8c7fd/3