用于删除重复值的SQL查询

时间:2017-03-22 19:59:26

标签: 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

请注意,查询删除了第一个记录,并保留了最后一个重复的值。

我认为结果是

 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 

4 个答案:

答案 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 

答案 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)

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

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