2009-06-09 137 views
1

說我有四個表交叉參考TSQL加入

1)Studnets:

  • student_id數據

2)聯繫方式(將採取最新產品)

  • CONTACT_ID
  • 地址
  • 郵編
  • DateAdded

3)電話(將採取最後三個項目)

  • CONTACT_ID
  • ******中國
  • DateAdded

4)StudentContactRef

  • student_id數據
  • CONTACT_ID

我如何可以查詢這個表?我想有場如下所示:

  • student_id數據
  • 地址
  • 郵編
  • PhoneNumber1
  • PhoneNumber2
  • PhoneNumber3
+1

如果您可以讓Phone具有與Contact_ID不同的Phone_Contact_ID,或者如果您可以向StudentContactRef表中添加「type」字段以指示您是否鏈接到聯繫人或電話號碼 – 2009-06-09 04:25:42

回答

1
select 
    s.Student_ID, 
    s.FirstName, 
    s.LastName, 
    c.Contact_ID, 
    c.Address, 
    c.ZipCode, 
    p.PhoneNumber1, 
    p.PhoneNumber2, 
    p.PhoneNumber3 
from 
    Students s 
    inner join StudentContactRef r on 
     s.Student_ID = r.StudentID 
    inner join Contact c on 
     r.Contact_ID = c.Contact_ID 
    inner join 
     (select top 3 Contact_ID, PhoneNumber from Phone 
     pivot (PhoneNumber for PhoneNumber IN 
      (PhoneNumber1, PhoneNumber2, PhoneNumber3) 
     where Contact_ID = r.Contact_ID order by DateAdded desc) p on 
     r.Contact_ID = p.Contact_ID 

更新:這應該讓你找到你想要的!