Sample Header Ad - 728x90

Fixing data pivot/grouping with db2

2 votes
0 answers
1124 views
I have a pretty straightforward sql query that I'm running on DB2 I-series 4 which is just performing some simple joins. The issue is that my materials table has it so that multiple material/color combos can be used on each body of work. Right now I'm getting rows of every combination but I want to consolidate so that if the value of test.materials.sequence is 2 then it creates two additional columns (if there's no sequence 2 for the combination then it would just be 0 and 0 in those columns. A working fiddle is here: https://www.db-fiddle.com/f/u4zKAdw3H4hFLbfnzEeZS2/1 THe query:
WITH ALLROWS AS(
  SELECT BOD.CODE 
         ,STM.SEQUENCE
         ,MAT.MATERIAL
         ,MAT.MAT_COLOR
    FROM SKUS SK
     INNER JOIN BODIES BOD ON SK.BODY_ID = BOD.ID
     INNER JOIN CATEGORIES PRC ON PRC.ID = SK.CATEGORY_ID
     INNER JOIN SKUS_TO_MATERIALS STM ON SK.ID = STM.SKU_ID
     INNER JOIN MATERIALS MAT ON STM.MAT_ID = MAT.ID
)
SELECT 
  CODE
  , MAX(CASE WHEN SEQUENCE = 1 THEN MATERIAL ELSE '0' END) AS MATERIAL1
  , MAX(CASE WHEN SEQUENCE = 1 THEN MAT_COLOR ELSE '0' END) AS COLOR1
  , MAX(CASE WHEN SEQUENCE = 2 THEN MATERIAL ELSE '0' END) AS MATERIAL2
  , MAX(CASE WHEN SEQUENCE = 2 THEN MAT_COLOR ELSE '0' END) AS COLOR2
FROM ALLROWS
GROUP BY CODE,MATERIAL,MAT_COLOR
order by CODE ASC;
This is my current result: | CODE | MATERIAL1 | COLOR1 | MATERIAL2 | COLOR2 | | ---- | --------- | ------ | --------- | ------ | | BodA | Fabric | Black | 0 | 0 | | BodA | Fabric | White | 0 | 0 | | BodA | Leather | Black | Leather | Black | | BodA | Leather | Brown | 0 | 0 | | BodB | Fabric | Black | 0 | 0 | | BodB | 0 | 0 | Leather | Black | | BodC | Leather | Brown | 0 | 0 | | BodD | Fabric | Black | 0 | 0 | --- This is the result I would want: | CODE | MATERIAL1 | COLOR1 | MATERIAL2 | COLOR2 | | ---- | --------- | ------ | --------- | ------ | | BodA | Fabric | Black | 0 | 0 | | BodA | Fabric | White | 0 | 0 | | BodA | Leather | Black | Leather | Black | | BodA | Leather | Brown | 0 | 0 | | BodB | Fabric | Black | Leather | Black | | BodC | Leather | Brown | 0 | 0 | | BodD | Fabric | Black | 0 | 0 | See how BodB should be a single row Is there a way through grouping and row-operations to achieve this?
Asked by Geoff_S (121 rep)
Dec 8, 2022, 02:35 PM