2011-09-16 293 views
3

可能重複:
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 

我有一個)dublicate記錄,以獲取輸出(下一個(順序應從結果集中排除):

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

所以,問題是比'選擇分鐘(一)更加複雜,B 從... 組由B'? - 因爲這將與您的示例數據 – antlersoft

+0

@antlersoft一起工作,這已經足夠了。我有:a是int並且b是唯一標識符,所以它也可以工作。謝謝。 – garik

回答

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

如果有非數字條目會怎麼樣? – Pepe

+0

@ P.R - 你應該仍然可以使用'min()'。 –

+0

它崩潰,並說它無法轉換爲數字(我在MS上試過) – Pepe

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的解決方案,我會在這裏雖然離開這個給後人。

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 
+1

獨特不會做任何事情,因爲你正在按b分組並且在a上使用aggegate,每一行都已經被升級爲獨特。 – TimothyAWiseman