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
 General SQL Server Forums
 New to SQL Server Programming
 Convert column to a row

Author  Topic 

lyndontrm
Starting Member

1 Post

Posted - 2012-08-21 : 11:04:16
Hello everyone,

I am a newbie to sql and I am faced with the problem below.

I have 3 tables

Categories
Cat_ID | Cat_Name
1 | Cosmetics
2 | Hair
3 | Furniture
4 | Office

Products
Prod_ID | Prod_name
1 | Chair
2 | Gel


Product_categories
Prod_ID | Cat_id
1 | 3
1 | 4
2 | 1
2 | 2

I need a query that will give me the following
Product | Categories
Chair | Furniture , Office
Gel | Cosmetics, Hair

Any help would be greatly appreciated

Regards,

Lyndon

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-08-21 : 11:10:12
[code]
;With ProdCat
AS
(
SELECT p.Prod_Name,c.Cat_Name
FROM Product p
INNER JOIN Product_categories pc
ON pc.Prod_ID = p.Prod_ID
INNER JOIN Categories c
ON c.Cat_ID = pc.Cat_ID
)

SELECT p.Prod_name AS Product,
STUFF((SELECT ',' + Cat_Name
FROM ProdCat
WHERE Prod_Name = p.Prod_Name
ORDER BY Cat_ID
FOR XML PATH('')),1,1,'') AS Categories
FROM (SELECT DISTINCT Prod_name FROM ProdCat)p
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -