用于计算重复项的 SQL 查询 [重复]
Posted
技术标签:
【中文标题】用于计算重复项的 SQL 查询 [重复]【英文标题】:SQL query to count duplicates [duplicate] 【发布时间】:2017-10-10 14:59:04 【问题描述】:请帮助我获取一个查询以计算重复项和一个查询以删除重复项。
【问题讨论】:
提示:查看GROUP BY
。
google.co.uk/search?q=sql+query+count+duplicates
你开始查询了吗,你能写什么SQL吗?
阅读***.com/help/how-to-ask。然后添加示例表数据和预期结果 - 以及格式化文本。并向我们展示您当前的查询尝试。并标记您正在使用的 dbms!
试试这个 DELETE FROM tblUsers WHERE ID IN (SELECT ID FROM tblUsers GROUP BY name, email HAVING COUNT(*) > 1)
【参考方案1】:
我同意所有的 cmets 所以请看How To Ask
如果这对你有用,并且为了它对我自己来说是一个很好的练习,它可以帮助其他人偶然发现这一点,这里有一些通用代码可以做到这一点:
WITH CTE AS
(
SELECT
COALESCE(Col1,'') AS Col1,
COALESCE(Col2,'') AS Col2, ROW_NUMBER() OVER(PARTITION BY col1,col2 ORDER BY col1,col2) AS row_id
FROM MyTable
)
DELETE CTE WHERE row_id >1;
例子:
Create table #things (FirstName varchar(10), LastName varchar(10))
insert into #things (FirstName, LastName)
values('thing','lastthing'),('thing','lastthing'),('otherthing', 'something')
select * from #things
;WITH CTE AS
(
SELECT
COALESCE(firstname,'') AS Col1,
COALESCE(lastname,'') AS Col2, ROW_NUMBER() OVER(PARTITION BY firstname,lastname ORDER BY firstname,lastname) AS row_id
FROM #things
)
DELETE CTE WHERE row_id >1;
select * from #things
drop table #things
【讨论】:
以上是关于用于计算重复项的 SQL 查询 [重复]的主要内容,如果未能解决你的问题,请参考以下文章