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.
Author |
Topic |
rankone
Starting Member
24 Posts |
Posted - 2013-11-21 : 00:33:16
|
Hey Everyone, So I have a table that has data which looks like this: (Example, the '---' are used to space the columns out) ID--------Product--------PriceUser 1----KitKat-------- 1.00User 1----Hersheys-------2.00User 2----KitKat-------- 1.00User 3----Nestle-------- 2.50User 1----Cadbury--------1.50User 3----Hersheys-------2.50User 2----Nestle-------- 0.50User 2----Cadbury--------3.00User 3----Nestle-------- 2.50User 3----KitKat-------- 4.00And I need to pivot it so that it looks like this: Product-------User 1-------User 2-------User 3KitKat--------$1.00--------$1.00--------$4.00Hersheys------$2.00--------$1.00--------$2.50Cadbury-------$1.50--------$3.00--------$1.00Nestle--------$1.00--------$0.50--------$2.50Any ideas on how I can go about this? Thanks |
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2013-11-21 : 01:04:54
|
[code]SELECT *FROM Table tPIVOT (SUM(Price) FOR ID IN ([User 1],[User 2],[User 3]))p[/code]------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
|
|
rankone
Starting Member
24 Posts |
Posted - 2013-11-21 : 02:10:16
|
The User 1, User 2, User 3 part is dynamic, so I can't have it set with column names. It doesn't have to be a column name, it can be part of the dataset as long as the result looks like what's shown in the original post. Thanks! |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2013-11-21 : 02:50:24
|
you can make it dynamic as belowDECLARE @UserList varchar(5000),@SQL varchar(max)SET @UserList = STUFF((SELECT DISTINCT ',['+ ID + ']' FROM Table FOR XML PATH('') ),1,1,'')SET @SQL ='SELECT *FROM Table tPIVOT (SUM(Price) FOR ID IN (' + @UserList + '))p'EXEC(@SQL) ------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs |
|
|
|
|
|
|
|