Search code examples
sqlteradata

How to combine multiple rows of one column into two columns in SQL


Thanks for any help. I was trying to generate multiple rows at target side for each row of source as shown below. I am using pivot in SQL to generate rows and need help with a SQL statement to match target expected data:

SELECT
    ID, CODES, 1 AS seq
FROM 
    TBL
UNPIVOT 
    (CODES FOR CPT_CDD IN (COL_1_CD,COL_1_CD_1)) AS P 
WHERE 
   COL_1_CD IS NOT NULL AND COL_1_CD_1 IS NOT NULL

UNION

SELECT
    ID, CODES, 2 AS seq
FROM 
    TBL
UNPIVOT 
    (CODES FOR CPT_CDD IN (COL_2_CD, COL_2_CD_1)) 
WHERE 
    COL_2_CD IS NOT NULL AND COL_2_CD_1 IS NOT 

UNION

SELECT
    ID, CODES, 2 AS seq
FROM
    TBL
UNPIVOT 
    (CODES FOR CPT_CDD IN (COL_2_CD, COL_2_CD_1)) 
WHERE 
    ((COL_2_CD IS NULL AND COL_2_CD_1 IS NOT NULL) 
     OR (COL_2_CD IS NOT NULL AND COL_2_CD_1 IS NULL))

UNION

SELECT
    ID, CODES, 1 AS seq
FROM
    TBL
UNPIVOT 
    (CODES FOR CPT_CDD IN (COL_2_CD, COL_2_CD_1)) 
WHERE 
    ((COL_1_CD IS NULL AND COL_1_CD_1 IS NOT NULL) 
     OR (COL_1_CD IS NOT NULL AND COL_1_CD_1 IS NULL))

UNION

SELECT 
    ID, NULL AS CODES, 3 AS seq
FROM
    TBL
WHERE 
    (COL_1_CD IS NULL AND COL_1_CD_1 IS NULL 
     AND COL_2_CD IS NULL AND COL_2_CD_1 IS NULL);

Data samples


Solution

  • Simply select the two columns that belong together and then use UNION to combine the two data sets and remove duplicates.

    select col_1_cd   as col_1_cds, col_2_cd   as col_2_cds  from mytable
    union
    select col_1_cd_1 as col_1_cds, col_2_cd_1 as col_2_cds  from mytable
    order by coalesce(col_1_cds, col_2_cds);