tags:

views:

19

answers:

1

Hello Guy,

I have been stuck on this problem for quite awhile... I hope someone out there can give me a hand.

The following table is in my database:

Product_ID Color   Type
1          Red     Leather
1          Silver  Metal
1          Blue    Leather
2          Orange  Metal
2          Purple  Metal

I am trying to get the following output:

Product_ID Type    Color
1          Leather Red, Blue
1          Metal   Silver
2          Metal   Orange, Purple

I know it has to do with some kind of double group by and a group_concat.... have been looking at this for an hour without figuring it out. Any help is much appreciated!!!

+1  A: 

Try this

SELECT Product_ID, Type, GROUP_CONCAT(Color)
FROM Products
GROUP BY Product_ID, Type

You didn't mention which database you are using - but I'm assuming MySQL since you mention GROUP_CONCAT.

mdma
+1, @DaveC remember that GROUP BY combines all rows with the same values in the columns listed in the GROUP BY. The aggregate function GROUP_CONCAT() takes the different values from all rows that need to be combined and makes a single value. The single value is then returned. So in this example, you get a single result set row for each unique combination of Product_ID and Type. Then, for each of those rows, the Color values are concatenated together by GROUP_CONCAT().
KM