关于如何在SQL Server中查找重复的行,Stack Overflow上有无数的示例。但我的目标是:
例如,我正在使用此查询在我的数据库中查找具有相同的Street_Number
,Street
和City
的所有交易:
WITH CTE AS
(
SELECT
ROW_NUMBER() OVER (PARTITION BY Street, Street_Number, City ORDER BY Street, Street_Number, City DESC) AS Counting,
*
FROM
GoogleDetails
)
SELECT *
FROM CTE
WHERE Counting > 1
ORDER BY Street_Number
但是此查询仅返回一行-我想同时看到它们。
答案 0 :(得分:2)
您可以尝试编写一个子查询,以通过COUNT
,Street
,Street_Number
来获得City
组,其数量大于1
,然后自我加入即可获得期望的行。
SELECT t2.*
FROM (
SELECT street,
street_number,
city
FROM googledetails
GROUP BY street,
street_number,
city
HAVING Count(*) > 1 ) t1
INNER JOIN googledetails t2
ON t1.street = t2.street
AND t1.street_number = t2.street_number
AND t1.city = t2.city
,或者您可以尝试使用EXISTS
进行修改。
SELECT t2.*
FROM googledetails t2
WHERE EXISTS
(
SELECT 1
FROM googledetails t1
WHERE t1.street = t2.street
AND t1.street_number = t2.street_number
AND t1.city = t2.city
GROUP BY t1.street,
t1.street_number,
t1.city
HAVING count(*) > 1 )
答案 1 :(得分:0)
简单来说,您可以尝试用count替换row_number,如下所示:
WITH CTE AS
(
SELECT
Count(*) OVER (PARTITION BY Street, Street_Number, City) AS Counting,
*
FROM
GoogleDetails
)
SELECT *
FROM CTE
WHERE Counting > 1
ORDER BY Street_Number
答案 2 :(得分:0)
存在但具有不同ID的其他方法,其性能优于使用分组依据:
SELECT f0.*
FROM googledetails f0
WHERE EXISTS
(
select * from googledetails f1
where f1.ID<>f0.ID and f1.street = f0.street
and f1.street_number = f0.street_number and f1.city = f0.city
)
答案 3 :(得分:0)
其他方法,交叉应用
SELECT f0.*
FROM googledetails f0
cross apply
(
select count(*) Counter
from googledetails f1
where f1.street = f0.street and f1.street_number = f0.street_number and f1.city = f0.city
) f2
where f2.Counter>1