3

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
Community
  • 1
  • 1
garik
  • 5,669
  • 5
  • 30
  • 42
  • 1
    So the question is more complicated than `select min(a), b from ... group by b`? -- because that would work with your example data – antlersoft Sep 16 '11 at 16:29
  • @antlersoft it is good enough. I have: a is int and b is uniqueidentifier, so it will work too. thank you. – garik Sep 16 '11 at 20:11

3 Answers3

4
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
Mikael Eriksson
  • 136,425
  • 22
  • 210
  • 281
1

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.

Michael Holman
  • 901
  • 1
  • 10
  • 26
1

The easiest way to do this is with a simple GROUP BY:

SELECT
      a
    , b
INTO #tmp
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


SELECT DISTINCT MIN(a) AS a,b
FROM #tmp
GROUP BY b
ORDER BY a
Wil
  • 4,130
  • 1
  • 16
  • 15
  • 1
    The distinct won't do anythin as you are grouping by b and usin an aggegate on a, each row would already be gaurunteed to be distinct. – TimothyAWiseman Sep 16 '11 at 16:50