我有一个包含这样的列的表。
id phone1 phone2 Phone3 Phone4 phone5
我希望id's
找到任何其他phonenumbers
匹配的{{1}}。我用Google搜索并搜索了这个网站,但没有找到答案。
提前谢谢。
// NISSE
答案 0 :(得分:4)
使用这样的模型你必须这样:
SELECT id
FROM dbo.TableName
WHERE phone1 = phone2
OR phone1 = phone3
OR phone1 = phone4
OR phone1 = phone5
OR phone2 = phone3
OR phone2 = phone4
OR phone2 = phone5
OR phone3 = phone4
OR phone3 = phone5
OR phone4 = phone5
如果你有另一张桌子存放那些通过外键链接的电话号码,你可以这样做:
SELECT t.id
FROM dbo.TableName t INNER JOIN dbo.PhoneNumbers p
ON t.ID = p.FkID
GROUP BY id
HAVING COUNT(p.PhoneNumber) <> COUNT(DISTINCT p.PhoneNumber)
答案 1 :(得分:1)
另一种方法是将cross apply
与table valued constructor
SELECT id
FROM Yourtable
CROSS apply (VALUES ('Phone1',Phone1),
('Phone2',Phone2),
('Phone3',Phone3),
('Phone4',Phone4),
('Phone5',Phone5)) cs(cname, data)
GROUP BY id,
data
HAVING Count(1) > 1
答案 2 :(得分:0)
如果您使用的是Name-Value对模型,那么您所要做的就是对您的表进行UNPIVOT,以使其返回数据的外观。如果您没有使用名称 - 值对表,我建议您重新考虑表的设计。
答案 3 :(得分:0)
您可以使用UNION ALL:
WITH cte AS (
SELECT id, phone1 AS phone FROM mytable
WHERE phone1 IS NOT NULL
UNION ALL
SELECT id, phone2 AS phone FROM mytable
WHERE phone2 IS NOT NULL
UNION ALL
SELECT id, phone3 AS phone FROM mytable
WHERE phone3 IS NOT NULL
UNION ALL
SELECT id, phone4 AS phone FROM mytable
WHERE phone4 IS NOT NULL
UNION ALL
SELECT id, phone5 AS phone FROM mytable
WHERE phone5 IS NOT NULL
)
SELECT id FROM (
SELECT id, phone, COUNT(*) FROM cte
GROUP BY id, phone
HAVING COUNT(*) > 1
) dup;