Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL No Dup (Distinct) on rows, but ignore one col

Tags:

sql

distinct

For Example, Table with three cols and data

col1  col2  col3
 10    20    30
 40    50    60
 40    50    80

Want to do a select where for the last two rows only returns one since col1 and col2 are the same.

select distinct will not work since col3 are different.

so output would be

 10 20 30
 40 50 xx (don't care)
like image 239
ort11 Avatar asked Feb 02 '12 16:02

ort11


1 Answers

As you only have one additional column you can just use an arbitrary MIN/MAX aggregate and GROUP BY

SELECT col1,
       col2,
       MAX(col3) AS col3
FROM   YourTable
GROUP  BY col1,
          col2  

More generally if your RDBMS supports analytic functions you can use

WITH T
     AS (SELECT col1,
                col2,
                col3,
                ROW_NUMBER() OVER (PARTITION BY col1, col2 
                                       ORDER BY col1, col2) AS RN
         FROM   YourTable)
SELECT col1,
       col2,
       col3
FROM   T
WHERE  RN = 1  
like image 66
Martin Smith Avatar answered Oct 18 '22 09:10

Martin Smith