重复删除

时间:2011-09-16 16:21:02

标签: tsql sql-server-2008 duplicate-removal

  

可能重复:
  Delete duplicate records from a SQL table without a primary key

我有数据:

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

我必须得到输出(下一步(按 a 排序),应从结果集中排除出版记录):

a           b
----------- -----------
1           30
2           50
3           50  -- should be excluded
4           50  -- should be excluded
5           60

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

在oracle中我能够使用group by子句来做到这一点,你应该可以做类似的事情。

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;

编辑:看起来像其他人想出了一个MS sql解决方案,我会留在这里为后人留下。

答案 2 :(得分:1)

最简单的方法是使用简单的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