I would like to do a pivot table on two tables I have.
table 1
PersonToPhone
PersonID int not null
phoneID int not null
table2
Phone
phoneID int not null
PhoneNumber nvarchar(10)
PhoneType int
I would like the result to be
---------|-------------|-------------|-------------|
personID | phoneNumber开发者_运维问答 | phoneNumber | phoneNumber |........ n times
is there a way of using a pivot table or some cool sql that will list a personID and all their phonenumbers on 1 row?
select personID,[Foo],[Bar],[fooBar]
FROM (
SELECT pp.PersonID,phonetype,phoneNumber
FROM personToPhone AS PP
inner join phone as p on pp.phoneid = p.phoneid
where pp.personid = @PersonID) as tableToPivot
pivot (max(phoneNumber) for phoneType IN ([[Foo],[Bar],[fooBar])) as pivotTable
Yanked most of the theory off of here http://sqlwithmanoj.wordpress.com/2011/01/25/dynamic-pivot/
精彩评论