我有以下模式的学区,Tehsil,学校代码和学校名称:
District Tehsil SchCode SchName
A AA 11111111 AA1
A AA 11111111 AA2
A AA 11111111 AA3
B BB 22222222 BB1
B BB 22222222 BB2
B BB 22222222 BB3
我想检查SchCode中的重复是否将相同的SchCode分配给具有相同或不同SchName的任何其他学校。
请为此建议SQL Server查询。我正在使用SQL Server 2008 Exp
答案 0 :(得分:1)
您可以加入按该列分组的相关子查询:
SELECT t1.District, t1.Tehsil, t1.SchCode, t1.SchName
FROM dbo.TableName t1
INNER JOIN (SELECT SchCode
FROM dbo.TableName
GROUP BY SchCode HAVING COUNT(*) > 1) dup
ON t1.SchCode = dup.SchCode
Sql-fiddle返回所有行,因为它们都是另一行的重复。
如果您只是想知道某条记录是否有重复内容,则可以使用此查询:
SELECT t1.District, t1.Tehsil, t1.SchCode, t1.SchName,
hasDuplicate = CASE WHEN dup.SchCode IS NULL THEN 'no' ELSE 'yes' END
FROM dbo.TableName t1
LEFT OUTER JOIN (SELECT SchCode
FROM dbo.TableName
GROUP BY SchCode HAVING COUNT(*) > 1) dup
ON t1.SchCode = dup.SchCode
Sql-fiddle已修改数据以获得非重复数据。
答案 1 :(得分:0)
试试这个
;WITH cte AS
(SELECT Row_number() OVER (partition BY schcode ORDER BY schname) id,*
FROM tablename )
SELECT *
FROM tablename a
JOIN (SELECT id,schcode ,count(1)
FROM cte
GROUP BY id,schcode
HAVING Count(1) > 1)) B
ON a.schcode = b.schcode
或
SELECT *
FROM tablename a
JOIN (SELECT schname,schcode ,count(1)
FROM tablename
GROUP BY schname,schcode
HAVING Count(1) > 1)) B
ON a.schcode = b.schcode