1

I have a table product and two columns id,pricing_category, and I have a query

SELECT DISTINCT ppp.`id` AS productid ,ppp.`pricing_category` AS type1
FROM `product` ppp
WHERE ppp.`finish_product_id`=1

The result is:

enter image description here

I want that type will appear as type1,type2,type3 in a single row for one id. How should I do it?

jarlh
  • 42,561
  • 8
  • 45
  • 63
USERRR5
  • 430
  • 2
  • 10
  • 27
  • 1
    Possible duplicate of [Can I concatenate multiple MySQL rows into one field?](http://stackoverflow.com/questions/276927/can-i-concatenate-multiple-mysql-rows-into-one-field) – tafa May 30 '16 at 12:05

2 Answers2

1

You can do it using conditional aggregation:

SELECT t.productID,
       MAX(CASE WHEN t.type1 = 1 THEN 1 ELSE 0 END) as type1_ind,
       MAX(CASE WHEN t.type1 = 2 THEN 1 ELSE 0 END) as type2_ind,
       MAX(CASE WHEN t.type1 = 3 THEN 1 ELSE 0 END) as type3_ind
FROM YourTable t
GROUP BY t.productID

This is dynamic for all productID, not just a specific one. To select a specific one, replace the group by with your WHERE clause.

This will return an indication for each product on every type if he has it(1) or not(0).

So for example for the data:

PRODUCTID | Type1
   1          1
   1          2
   1          3
   2          3

This will return:

PRODUCTID | TYPE1_IND | TYPE2_IND | TYPE3_IND
    1           1            1           1
    2           0            0           1

Or to get them all as one column use GROUP_CONCAT()

SELECT t.productID,
       GROUP_CONCAT(concat('TYPE',t.type1))
FROM YourTable t
GROUP BY t.productID
sagi
  • 40,026
  • 6
  • 59
  • 84
0

You can use GROUP_CONCAT :

select id productid,
       group_concat(concat('type', pricing_category) order by pricing_category) type
from product
where finish_product_id = 1
group by id;

See SQLFiddle

ebahi
  • 536
  • 2
  • 7