Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicates removing [duplicate]

Possible Duplicate:
Delete duplicate records from a SQL table without a primary key

I have data:

SELECT
          a
        , b
    FROM 
    (
        select a = 1, b = 30
        union all 
        select a = 2, b = 50
        union all 
        select a = 3, b = 50
        union all 
        select a = 4, b = 50
        union all 
        select a = 5, b = 60
    ) t

I have to get output (next (order by a) dublicate records should be excluded from result set):

a           b
----------- -----------
1           30
2           50
3           50  -- should be excluded
4           50  -- should be excluded
5           60
like image 747
garik Avatar asked Aug 27 '26 18:08

garik


2 Answers

SELECT
          min(a) as a
        , b
    FROM 
    (
        select a = 1, b = 30
        union all 
        select a = 2, b = 50
        union all 
        select a = 3, b = 50
        union all 
        select a = 4, b = 50
        union all 
        select a = 5, b = 60
    ) t
GROUP BY b    
ORDER BY a
like image 72
Mikael Eriksson Avatar answered Aug 31 '26 09:08

Mikael Eriksson


In oracle I was able to do this using a group by clause, you should be able to do similar.

select min(a), b
 from (select 1 a, 30 b
        from dual
      union all
      select 2 a, 50 b
        from dual
      union all
      select 3 a, 50 b
        from dual
      union all
      select 4 a, 50 b
        from dual
      union all
      select 5 a, 60 b from dual)
group by b;

edit: looks like someone else came up with a MS sql solution, I'll leave this here for posterity though.

like image 33
Michael Holman Avatar answered Aug 31 '26 11:08

Michael Holman