billsecond
billsecond

Reputation: 612

Cross Reference TSQL Join

Say i have Four tables

1) Studnets:

2) Contact (Will take the latest item)

3) Phone (Will take the last three items)

4) StudentContactRef

How can I query this table? I want to have the fields as shows below:

Upvotes: 1

Views: 728

Answers (1)

Eric
Eric

Reputation: 95153

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

Update: That should get you what you're looking for!

Upvotes: 1

Related Questions