user281693
user281693

Reputation: 635

Need help with pivot for this table sql server

I have a table with the following structure

uid  sid  eid   Key     value
1    1     1   F.Name   Simon 
2    1     1   L.Name   Jones
3    1     1   C.Name   AAPL
4    1     1   Address  Infinite
5    2     1   F.Name   Brad
6    2     1   L.Name   Pitt
7    2     1   C.Name   Holly
8    2     1   Address  LA

I would like to convert the above table to below format

sid  F.Name  L.Name  C.Name  Address
1    Simon   Jones   AAPL    Infinite
2    Brad    Pitt    Holly   LA

Basically I need values of "Key" column to be column fields in new table. I have no other table. Even Linq to sql is ok and I can understand it.

Upvotes: 1

Views: 211

Answers (1)

Quassnoi
Quassnoi

Reputation: 425411

In 2005 and later:

SELECT  *
FROM    (
        SELECT  sid, key, value
        FROM    mytable
        ) q
PIVOT   (
        MIN(value)
        FOR
        key IN ([F.Name], [L.Name], [C.Name], [Address])
        ) p

Upvotes: 1

Related Questions