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 2008 Forums
 Transact-SQL (2008)
 Row to column
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

rychlous
Starting Member

1 Posts

Posted - 03/02/2014 :  10:47:04  Show Profile  Reply with Quote
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

India
52325 Posts

Posted - 03/02/2014 :  12:51:41  Show Profile  Reply with Quote

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


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

visakh16
Very Important crosS Applying yaK Herder

India
52325 Posts

Posted - 03/02/2014 :  12:52:47  Show Profile  Reply with Quote
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

India
334 Posts

Posted - 03/03/2014 :  14:06:40  Show Profile  Reply with Quote
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

India
334 Posts

Posted - 03/03/2014 :  16:05:22  Show Profile  Reply with Quote
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
  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.05 seconds. Powered By: Snitz Forums 2000