crompnk
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
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
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
FORGOT TO MENTION REPLACE YourTable WITH WHATEVER TABLE YOU ARE USING.