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.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Need help to Pivot data

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--------Price
User 1----KitKat-------- 1.00
User 1----Hersheys-------2.00
User 2----KitKat-------- 1.00
User 3----Nestle-------- 2.50
User 1----Cadbury--------1.50
User 3----Hersheys-------2.50
User 2----Nestle-------- 0.50
User 2----Cadbury--------3.00
User 3----Nestle-------- 2.50
User 3----KitKat-------- 4.00

And I need to pivot it so that it looks like this:

Product-------User 1-------User 2-------User 3
KitKat--------$1.00--------$1.00--------$4.00
Hersheys------$2.00--------$1.00--------$2.50
Cadbury-------$1.50--------$3.00--------$1.00
Nestle--------$1.00--------$0.50--------$2.50

Any 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 t
PIVOT (SUM(Price) FOR ID IN ([User 1],[User 2],[User 3]))p
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

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!
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-11-21 : 02:50:24
you can make it dynamic as below


DECLARE @UserList varchar(5000),@SQL varchar(max)

SET @UserList = STUFF((SELECT DISTINCT ',['+ ID + ']' FROM Table FOR XML PATH('') ),1,1,'')

SET @SQL ='SELECT *
FROM Table t
PIVOT (SUM(Price) FOR ID IN (' + @UserList + '))p'

EXEC(@SQL)


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -