自联接中的SQL查询问题

时间:2012-03-16 07:22:23

标签: sql-server-2005

我有一个名为customer的表,其中包含这样的列

 CustomerID  primaryCustID   Phonenumber  Mobilenumber
 1              1               11111       983433453
 2              2               22222       564647844
 3              3               33333       983344354
 4              4               44444       983434232
 5              2               55555       983436790
 6              4               66666       983431111
 7              4               77777       983434444
 8              8               88888       983437777
 9              3               99999       983439999

现在我需要得到这样的输出

CustomerID  primaryCustID   Phonenumber1  Mobilenumber1       Phonenumber2      Mobilenumber2
 5              2               55555       983436790           22222           564647844
 6              4               66666       983431111           44444           983434232
 7              4               77777       983434444           44444           983434232
 9              3               99999       983439999           33333           983344354

select e.CustomerID, m.primaryCustID ,e.Phonenumber1 "Phonenumber1", 
e.Mobilenumber "Mobilenumber1", m.Phonenumber1 "Phonenumber2",
m.Mobilenumber "Mobilenumber2" from Customer e,
Customer m where e.CustomerID<>m.primaryCustID

我试过这样但没有得到例外结果

任何想法如何解决这个问题,任何帮助都会很棒。

由于

王子

1 个答案:

答案 0 :(得分:3)

您忘记添加joinprimaryCustID连接的CustomerID条件。

select C1.CustomerID,
       C1.primaryCustID,
       C1.Phonenumber as Phonenumber1,
       C1.Mobilenumber as Mobilenumber1,
       C2.Phonenumber as Phonenumber2,
       C2.Mobilenumber as Mobilenumber2
from Customer as C1
  inner join Customer as C2
    on C1.primaryCustID = C2.CustomerID
where C1.CustomerID <> C1.primaryCustID