Convert three rows values into columns, NOT as comma separated value

Conditional aggregation is an option:

SELECT
   catalog_item_id,
   MAX(CASE WHEN rn % 3 = 1 THEN CONCAT(metal_type, '/', metal_color) END) AS Casting_1,
   MAX(CASE WHEN rn % 3 = 2 THEN CONCAT(metal_type, '/', metal_color) END) AS Casting_2,
   MAX(CASE WHEN rn % 3 = 0 THEN CONCAT(metal_type, '/', metal_color) END) AS Casting_3
FROM (
   SELECT 
      catalog_item_id, metal_type, metal_color, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS rn
   FROM (VALUES
      (465173, 'na', 'METALCOLOR'),
      (465173, 'na', 'METAL-001'),
      (465173, 'na', 'na')
   ) catalog_item_castings (catalog_item_id, metal_type, metal_color) 
   WHERE catalog_Item_Id = 465173
) t   
GROUP BY catalog_item_id
-- or if you have more than three rows per [catalog_item_id]
-- GROUP BY catalog_item_id, (rn - 1) / 3 

Result:

catalog_item_id Casting_1     Casting_2    Casting_3
-------------------------------------------------
465173          na/METALCOLOR na/METAL-001 na/na

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top