开发者

sql pivot table or something like a pivot table

开发者 https://www.devze.com 2023-03-06 10:51 出处:网络
I would like to do a pivot table on two tables I have. table 1 PersonToPhone PersonID int not null phoneID int not null

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/

0

精彩评论

暂无评论...
验证码 换一张
取 消