2013-07-04 53 views
5

我目前有一個名爲People的表。在這個表有成千上萬行數據,其遵循以下佈局:刪除1個重複值的實例T-SQL

gkey | Name | Date  | Person_Id 
1 | Fred | 12/05/2012 | ABC123456 
2 | John | 12/05/2012 | DEF123456 
3 | Dave | 12/05/2012 | GHI123456 
4 | Fred | 12/05/2012 | JKL123456 
5 | Leno | 12/05/2012 | ABC123456 

如果我執行以下命令:

SELECT [PERSON_ID], COUNT(*) TotalCount 
FROM [Database].[dbo].[People] 
GROUP BY [PERSON_ID] 
HAVING COUNT(*) > 1 
ORDER BY COUNT(*) DESC 

我得到的回報:

Person_Id  | TotalCount 
ABC123456  | 2 

現在我想刪除只有一行重複值,所以當我執行上述查詢時,我沒有返回任何結果。這可能嗎?

+0

我不能看到重複的值,你想刪除弗雷德或萊諾(誰擁有相同的Person_ID)?是否有做出這樣的決定的規則? –

回答

7
WITH a as 
(
SELECT row_number() over (partition by [PERSON_ID] order by name) rn 
FROM [Database].[dbo].[People] 
) 
DELETE FROM a 
WHERE rn = 2 
+0

謝謝。欣賞它 – LaLa

0

試試這個

DELETE FROM [People] 
WHERE gkey IN 
(
    SELECT MIN(gkey) 
    FROM [People] 
    GROUP BY [PERSON_ID] 
    HAVING COUNT(*) > 1 
) 

您可以使用MINMax

0
DELETE FROM PEOPLE WHERE gkey= 
(SELECT MAX(TABLE1.gkey) FROM (SELECT P.gkey, A.PERSON_ID,A.TotalCount FROM People P,(SELECT [PERSON_ID], COUNT(*) TotalCount 
FROM [Database].[dbo].[People] 
GROUP BY [PERSON_ID] 
HAVING COUNT(*) > 1 
ORDER BY COUNT(*) DESC) A WHERE P.gkey=A.gkey) TABLE1) TABLE2 
0

與刪除使用TOP關鍵字;

DELETE TOP(1) FROM [People] 
WHERE Person_Id IN 
(
    SELECT MIN([PERSON_ID]) 
    FROM [People] 
    GROUP BY [PERSON_ID] 
    HAVING COUNT(*) > 1 

查詢是一樣張貼Vassy酒店只有頂(1)addded ...