三列在一个表下具有相同的值,如何获取所有列中可用的值

时间:2018-05-24 15:32:59

标签: sql-server

考虑下表:

Phone1     Phone2   Phone3
123458    25689     8969860
25966     25966     123458
Null      123458     25966

我想获取其他电话列中可用的Phone1值的记录。

1 个答案:

答案 0 :(得分:2)

这是一个答案,甚至毫无疑问:D

DECLARE @MYTAB TABLE(PHONE1 INT, PHONE2 INT, PHONE3 INT)
INSERT INTO @MYTAB VALUES

(123458,    25689,     8969860),
(25966,     25966,     123458),
(Null,      123458,     25966)

SELECT T1.PHONE1
FROM @MYTAB T1
WHERE EXISTS(SELECT 1 FROM @MYTAB T2 WHERE T2.PHONE2 = T1.PHONE1)
AND EXISTS (SELECT 1 FROM @MYTAB T3 WHERE T3.PHONE3 = T1.PHONE1)

与以下内容相同:

SELECT T1.PHONE1
FROM @MYTAB T1
INNER JOIN @MYTAB T2 ON T2.PHONE2 = T1.PHONE1
INNER JOIN @MYTAB T3 ON T3.PHONE3 = T1.PHONE1