删除带有计数(*)>的语句1

时间:2018-02-14 11:38:38

标签: sql sql-server sql-server-2012

我希望删除的表格中有一些重复。但是,SQL不喜欢我的查询。

delete from tblS
where Field = 'spread'
group by FundCode, Region, DateEntered
having count(*) > 1

所以我再次尝试了下面的查询,尽管SQL并不喜欢这样。我的查询应该怎么样?

delete s
from tblS s
join
(
    select FundCode, Region, DateEntered, count(*)
    from tblS 
    where Field = 'spread'
    group by FundCode, Region, DateEntered
    having count(*) > 1
) as d on s.FundCode = d.FundCode and s.DateEntered = d.DateEntered and s.Region= d.Region

1 个答案:

答案 0 :(得分:2)

通常,当您想要删除重复项时,您希望保留其中一个副本。正确使用的函数是row_number(),SQL Server支持可更新的CTE。所以:

with toupdate as (
      select t.*,
             row_number() over (partition by FundCode, Region, DateEntered order by FundCode) as seqnum
      from tblS t
      where Field = 'spread'
     )
delete toupdate
    where seqnum > 1;

如果您确实要删除所有重复项,请使用count(*)代替row_number()