Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
HelloI'm trying to convert some data from a column format into rows.I've done something similar in the past going from rows into columns but this seems a bit trickier to do and I could do with some help.I currently have the data in the following format:FIRSTNAME__LASTNAME__VAL1__VAL2__VAL3__VAL4JOHN_______SMITH_____2_____3_____1_____9PETER______jONES_____4_____6_____2_____1SARAH______KELLY_____5_____2_____1_____6What I need is the data to be in the following format:FIRSTNAME__LASTNAME__ITEM__VALJOHN_______SMITH_____VAL1__2JOHN_______SMITH_____VAL2__3JOHN_______SMITH_____VAL3__1JOHN_______SMITH_____VAL4__9PETER______jONES_____VAL1__4PETER______jONES_____VAL2__6PETER______jONES_____VAL3__2PETER______jONES_____VAL4__1SARAH______KELLY_____VAL1__5SARAH______KELLY_____VAL2__5SARAH______KELLY_____VAL3__1SARAH______KELLY_____VAL4__6Is there a way of getting it in to the above format incorporating the VAL columns in to one columun containing the VAL rows?Thanks in advance.
visakh16
Very Important crosS Applying yaK Herder
52326 Posts
Posted - 2009-02-13 : 09:28:26
[code]SELECT FIRSTNAME,LASTNAME,ITEM,VALFROM(SELECT FIRSTNAME,LASTNAME,VAL1,VAL2,VAL3,VAL4 FROM Table)mUNPIVOT (VAL FOR ITEM IN ([VAL1],[VAL2],[VAL3],[VAL4]))u[/code]
nr
SQLTeam MVY
12543 Posts
Posted - 2009-02-13 : 09:28:49
select firstname, lastname, item = 'val1', val = val1 from tblunion allselect firstname, lastname, item = 'val2', val = val2 from tblunion all......==========================================Cursors are useful if you don't know sql.DTS can be used in a similar way.Beer is not cold and it isn't fizzy.
visakh16
Very Important crosS Applying yaK Herder
52326 Posts
Posted - 2009-02-13 : 09:30:37
Also
SELECT FIRSTNAME,LASTNAME,ITEM,VALFROM(SELECT FIRSTNAME,LASTNAME,'VAL1' AS ITEM,VAL1 AS VALFROM TableUNION ALLSELECT FIRSTNAME,LASTNAME,'VAL2',VAL2FROM TableUNION ALLSELECT FIRSTNAME,LASTNAME,'VAL3',VAL3FROM TableUNION ALLSELECT FIRSTNAME,LASTNAME,'VAL4',VAL4FROM Table)t