SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Need help to Pivot data
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

rankone
Starting Member

24 Posts

Posted - 11/21/2013 :  00:33:16  Show Profile  Reply with Quote
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

India
52317 Posts

Posted - 11/21/2013 :  01:04:54  Show Profile  Reply with Quote

SELECT *
FROM Table t
PIVOT (SUM(Price) FOR ID IN ([User 1],[User 2],[User 3]))p


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

rankone
Starting Member

24 Posts

Posted - 11/21/2013 :  02:10:16  Show Profile  Reply with Quote
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

India
52317 Posts

Posted - 11/21/2013 :  02:50:24  Show Profile  Reply with Quote
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
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.03 seconds. Powered By: Snitz Forums 2000