Search code examples
t-sqlsql-server-2012distinct-values

select all rows where column values are unique


There's a table T with columns n00, n01, n01, ..., n99, all integers.

I need to select all rows from this table where n00...n99 values are unique within each row.

Example for smaller number of columns:

columns: n0, n1, n2
row 1:   10, 20, 30
row 2:   34, 45, 56
row 3:   12, 13, 12
row 4:   31, 65, 90

I need the select statement to return rows 1, 2 and 4 but not 3 (row 3 contains non-unique value of 12 so filter it out).

Effectively I need to implement this:

select *
from t
where 
      n00 <> n01 and n00 <> n02 and ... and n00 <> n99
  and n01 <> n02 and n01 <> n03 and ... and n01 <> n99
  and n02 <> n03 and n02 <> n04 and ... and n02 <> n99
  ...
  and n97 <> n98 and n97 <> n99
  and n98 <> n99

... but with "smarter" WHERE block.

Any hints welcome.


Solution

  • You can use UNPIVOT as well:

    DECLARE @t TABLE(n0 int, n1 int, n2 int);
    INSERT INTO @t VALUES (10, 20, 30), (34, 45, 56), (12, 13, 12), (31, 65, 90);
    
    WITH cteRows AS(
      SELECT ROW_NUMBER() OVER (ORDER BY n0, n1, n2) rn, *
                 FROM @t
    ),
    cteUP AS(
      SELECT rn, rn_val
        FROM cteRows
      UNPIVOT(
        rn_val FOR rn_vals IN(n0, n1, n2)
      ) up
    ),
    cteFilter AS(
      SELECT rn, rn_val, count(*) anz
        FROM cteUP
        GROUP BY rn, rn_val
        HAVING count(*) > 1
    )
    SELECT *
      FROM cteRows
      WHERE rn NOT IN (SELECT rn FROM cteFilter)