2017-03-22 193 views
0

我有了SQL查詢刪除重複值

Account, CompanyID, Mail_Address 
1001,1,Main ST 
1001,2,Main ST 
1001,3,Florida ST 
1002,1,South Main 
1002,2,West Main 
1002,3,Soth Main 
1003,1,North Main 
1003,2,North Main 

我需要創建一個查詢,刪除重複MAIL_ADDRESS,這是很容易做到的表。問題是返回的結果是重複值的最後一個,而不是第一個重複的值。

如果我的桌子上面 結果會

Account, CompanyID, Mail_Address 
    1001,2,Main ST 
    1001,3,Florida ST 
    1002,2,West Main 
    1002,3,South Main 
    1003,2,North Main 

通知查詢刪除第一條記錄,並保持最後的重複值的。

我perfer結果是

Account, CompanyID, Mail_Address 
    1001,1,Main ST 
    1001,3,Florida ST 
    1002,1,South Main 
    1002,2,West Main 
    1003,1,North Main 

我的查詢

SELECT * 
    FROM (SELECT [ACCOUNT] 
     ,[COMPANY] 
     ,[MAIL_ADDRESS] 
     , 

     ROW_NUMBER() OVER(PARTITION BY Mail_Address ORDER BY Account ASC) rn 
        FROM [SQLUserDB].[dbo].[DSDD01]     

      ) a 
WHERE rn = 1 

回答

0

如果你是最低的公司的價值後,這將工作:

SELECT Account, MIN(Company) as Company, Mail_Address 
FROM SqlUserDb.dbo.DSDD01 
GROUP BY Account, Mail_Address 

如果你是後第一家上市公司價值,這將做到這一點,非常接近你有:

SELECT Account, Company, Mail_Address 
FROM (
    SELECT Account, Company, Mail_Address, 
    ROW_NUMBER() OVER(PARTITION BY Mail_Address ORDER BY Account, Company) CompanyRowNo 
    FROM SqlUserDb.dbo.DSDD01 
) x 
WHERE x.CompanyRowNo = 1 
+0

謝謝第一次工作。 –

1

只需添加另一個條件到ORDER BY

SELECT * 
    FROM (SELECT [ACCOUNT] 
     ,[COMPANY] 
     ,[MAIL_ADDRESS] 
     , 

     ROW_NUMBER() OVER(PARTITION BY Mail_Address ORDER BY Account ASC, CompanyID) rn 
        FROM [SQLUserDB].[dbo].[DSDD01]     

      ) a 
WHERE rn = 1 
0

可以使用not exists實現自己的意圖:

select Account, CompanyID, Mail_Address 
FROM [SQLUserDB].[dbo].[DSDD01] t1 
where not exists (select 1 
        from [SQLUserDB].[dbo].[DSDD01] t2 
        where t1.Mail_Address = t2.Mail_Address and t2.CompanyID < t1.CompanyID) 
0

只是爲了顯示你的另一種方法,使用表對自身內部聯接:

-- List Mail_Address to Delete 
select t1.Account, t1.CompanyID, t1.Mail_Address 
from [SQLUserDB].[dbo].[DSDD01] t1 
inner join [SQLUserDB].[dbo].[DSDD01] t2 
on t1.Account = t2.Account 
and t1.Mail_Address = t2.Mail_Address 
where t1.CompanyID > t2.Company_ID 

-- Delete Duplicate Mail_Address 
delete t1 
from [SQLUserDB].[dbo].[DSDD01] t1 
inner join [SQLUserDB].[dbo].[DSDD01] t2 
on t1.Account = t2.Account 
and t1.Mail_Address = t2.Mail_Address 
where t1.CompanyID > t2.Company_ID