我有一个包含两列CountryCode CountryName
的表格。 countrycode
中有重复的条目。但我想删除不重复的entires并保留countrycode
列中重复的行。所以我试着写一个SQL语句来做到这一点。我想我必须使用但不太确定如何合并它。感谢
答案 0 :(得分:2)
这有点奇怪。我希望你想要删除重复的条目,而不是相反。但无论您使用何种数据库,这样的事情都应该有效:
delete from TableName
where CountryCode in (select CountryCode
from TableName
group by CountryCode
having count(*) = 1).
所以要明确,子查询:
select CountryCode
from TableName
group by CountryCode
having count(*) = 1
...返回具有唯一CountryCodes
的行。然后是delete
声明:
delete from TableName
where CountryCode in (...)
...删除那些唯一的行,以便表中剩余的唯一行应该是具有重复项的行。
然而,通过您的评论,听起来您只想要一个只返回重复项的查询。如果是这种情况,那么只需在select
语句中使用子查询,但修改having
子句只返回重复项:
select *
from TableName
where CountryCode in (select CountryCode
from TableName
group by CountryCode
having count(*) > 1)
答案 1 :(得分:0)
这是一个快速的解决方案,它可能不是很多条目的精品,但它的工作原理。
SELECT * FROM [table] AS tbl
WHERE countrycode IN
(SELECT countrycode FROM [table] WHERE tbl.countryname <> countryname)
/* Words in uppercase are SQL Syntax */
命名第一个表格(
tbl
),您可以在嵌套查询中使用它