sqlteradatateradatasql

Teradata - Get unique values among the column in a row


How to obtain unique values from a set of columns for each row in a table. Consider the following table structure:

COL1 | COL2 | COL3 | COL4
--------------------------
  1  |  1   |  2   |  3
  2  |  2   |  2   |  4
  4  |  5   |  6   |  7

The desired result should look like this:

COL1 | COL2 | COL3 | COL4
--------------------------
  1  |  2   |  3   | NULL
  2  |  4   | NULL | NULL
  4  |  5   |  6   |  7

I was able to achieve this by case statements by comparing each columns with each other. Are there any other way to do this?


Solution

  • You could use UNPIVOT (or UNION) + PIVOT

    UNPIVOT - Get a row for each value of colN

    Rank them and get the distinct.

    PIVOT back to the original column list.

    CREATE VOLATILE TABLE some_data
    (
        COL1 INTEGER,
        COL2 INTEGER,
        COL3 INTEGER,
        COL4 INTEGER
    ) 
    ON COMMIT PRESERVE ROWS;
    
    INSERT INTO some_data (COL1, COL2, COL3, COL4) VALUES (1, 1, 2, 3);
    INSERT INTO some_data (COL1, COL2, COL3, COL4) VALUES (2, 2, 2, 4);
    INSERT INTO some_data (COL1, COL2, COL3, COL4) VALUES (4, 5, 6, 7);
    
    with 
    add_a_key as (
        select row_number() over ( order by 1) as a_key,
               sd.*
          from some_data sd),
    unpivot_ranked as (
        select distinct
               a_key,
               val,
               dense_rank() over ( 
                 partition by a_key
                     order by val ) as rn
          from add_a_key
          unpivot (
               val 
               for col in (col1, col2, col3, col4)
        ) as unpivoted
    )
    select col1,
           col2,
           col3,
           col4
      from unpivot_ranked
     pivot (
           sum(val) for rn in (1 as col1 ,
                               2 as col2,
                               3 as col3,
                               4 as col4)
           ) t
     order
        by col1;
    
    COL1 COL2 COL3 COL4
    1 2 3 ?
    2 4 ? ?
    4 5 6 7