sql查询获取冗余记录
我想从数据库中获取冗余记录。我的查询是否正确?
select (fields)
from DB
group by name, city
having count(*) > 1
如果错误,请告诉我如何纠正。
另外如果我想删除重复记录可以吗?
delete from tbl_name
where row_id in
(select row_id from tbl_name group by name, city having count(*) > 1)
所以我可以像这样进行上面的查询
DELETE FROM tb_name where row_id not in(select min(row_id) from tb_name groupBy(name, city) having count(*)>1)
I want to get redundant records from the database. Is my query correct for this?
select (fields)
from DB
group by name, city
having count(*) > 1
If wrong please let me know how can I correct this.
Also if I want to delete duplicate record will it work?
delete from tbl_name
where row_id in
(select row_id from tbl_name group by name, city having count(*) > 1)
so i can make the above query like this
DELETE FROM tb_name where row_id not in(select min(row_id) from tb_name groupBy(name, city) having count(*)>1)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的
DELETE
语法绝对是完全错误的 - 这永远不会起作用。它将执行的操作是删除出现多次的所有行 - 不留下任何数据...您在 SQL Server 2005 及更高版本中可以执行的操作是使用CTE(通用表表达式)和
ROW_NUMBER()
排名函数:您基本上通过
(name, city)
组合创建数据的“分区” - 每对都将获得从 1 开始的连续编号。那些出现多次的条目也会在该 CTE 中具有
RowNum > 的条目。 1
- 只需删除所有这些,您的重复项就完成了!了解在以下位置使用通用表表达式SQL Server 2005 以及SQL Server 2005 中的排名函数和性能(或查阅有关这些主题的 MSDN 文档)
Your
DELETE
syntax is definitely totally wrong - that won't work ever. What it'll do is delete all rows that have more than one occurence - not leaving any data around...What you can do in SQL Server 2005 and up is use a CTE (Common Table Expression) and the
ROW_NUMBER()
ranking function:You basically create "partitions" of your data by the
(name, city)
combo - each of those pairs will get sequential numbers from 1 on up.Those that have more than one occurence will also have entries in that CTE with a
RowNum > 1
- just delete all of those and your duplicates are done!Read about Using Common Table Expressions in SQL Server 2005 and about Ranking Functions and Performance in SQL Server 2005 (or consult the MSDN docs on those topics)
您的语法错误:
如果您对实际计数不感兴趣,请从查询中删除“
, count(*)
”You have the syntax wrong:
If you are not interested in the actual count, remove "
, count(*)
" from the query