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 2008 Forums
 Transact-SQL (2008)
 Row to column

Author  Topic 

rychlous
Starting Member

1 Post

Posted - 2014-03-02 : 10:47:04
Hello, how can i build query, which do this:

table - customer
id_customer: 1
name: Freddie

table - prices
id_price: 1
id_customer: 1
price_name: D1
price_value: 200

id_price: 2
id_customer: 1
price_name: D2
price_value: 100

required output
column names:   id_customer   name      D1     D2
column values:  1                 Freddie    200     100


Thank you!!

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2014-03-02 : 12:51:41
[code]
SELECT *
FROM
(
SELECT c.id_customer,c.name,pr.price_name,pr.price_value
FROM customer c
INNER JOIN prices pr
ON pr.id_customer = c.id_customer
)t
PIVOT (SUM(price_value) FOR price_name IN ([D1],[D2]))p
[/code]

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

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2014-03-02 : 12:52:47
To make it dynamic see
http://beyondrelational.com/modules/2/blogs/70/posts/10840/dynamic-pivot-in-sql-server-2005.aspx

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

sqllover
Constraint Violating Yak Guru

338 Posts

Posted - 2014-03-03 : 14:06:40
Hi Khtan,

Great code. having question about how to make it order by c.name?

I am also doing this pivot functionality and wondering is it possible to add the order by clause.

thanks
Go to Top of Page

sqllover
Constraint Violating Yak Guru

338 Posts

Posted - 2014-03-03 : 16:05:22
This is how i achieved. am all set


SELECT *
FROM
(
SELECT c.id_customer,c.name,pr.price_name,pr.price_value
FROM customer c
INNER JOIN prices pr
ON pr.id_customer = c.id_customer
)t
PIVOT (SUM(price_value) FOR price_name IN ([D1],[D2]))p
order by p.name
Go to Top of Page
   

- Advertisement -