Link to home
Start Free TrialLog in
Avatar of crompnk
crompnkFlag for United Kingdom of Great Britain and Northern Ireland

asked on

PIVOT SQL

Hi,
I would like to know the best way to pivot a table using sql.
The table that needs pivoting is below:

ID    TYPE      VALUE
1A      PLAN      Yes
1A      FINAL      No
1B      PLAN      Yes
1B      FINAL      No
1C      PLAN      Yes
1C      FINAL      No

The new table required is:

ID    PLAN   FINAL
1A      Yes          No
1B      Yes          No
1C      Yes          No

Thank you
CREATE TABLE [RESULT](
    [ID] [varchar](30) NOT NULL,
    [TYPE] [varchar](30) NOT NULL,
    [VALUE] [varchar](30) NOT NULL
)
GO

INSERT INTO RESULT VALUES('1A','PLAN','Yes')
INSERT INTO RESULT VALUES('1A','FINAL','No')
INSERT INTO RESULT VALUES('1B','PLAN','Yes')
INSERT INTO RESULT VALUES('1B','FINAL','No')
INSERT INTO RESULT VALUES('1C','PLAN','Yes')
INSERT INTO RESULT VALUES('1C','FINAL','No')
GO

select
ID
,min(CASE when [TYPE] = 'PLAN' then VALUE ELSE 'Null' END) as [PLAN] 
,min(CASE when [TYPE] = 'FINAL' then VALUE ELSE 'Null' END) as [FINAL] 
from RESULT 
group by ID
GO

DROP TABLE RESULT
GO

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Imran Javed Zia
Imran Javed Zia
Flag of Pakistan image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
FORGOT TO MENTION REPLACE YourTable WITH WHATEVER TABLE YOU ARE USING.