Search code examples
sqldb2ibm-cloud

Combine three columns from different tables into one row


I am new to sql and are trying to combine a column value from three different tables and combine to one row in DB2 Warehouse on Cloud. Each table consists of only one row and unique column name. So what I want to is just join these three to one row their original column names.

Each table is built from a statement that looks like this:

SELECT SUM(FUEL_TEMP.FUEL_MLAD_VALUE) AS FUEL 
FROM
    (SELECT ML_ANOMALY_DETECTION.MLAD_METRIC AS MLAD_METRIC, ML_ANOMALY_DETECTION.MLAD_VALUE AS FUEL_MLAD_VALUE, ML_ANOMALY_DETECTION.TAG_NAME AS TAG_NAME, ML_ANOMALY_DETECTION.DATETIME AS DATETIME, DATA_CONFIG.SYSTEM_NAME AS SYSTEM_NAME
     FROM ML_ANOMALY_DETECTION 
         INNER JOIN DATA_CONFIG ON 
               (ML_ANOMALY_DETECTION.TAG_NAME  =DATA_CONFIG.TAG_NAME AND 
                DATA_CONFIG.SYSTEM_NAME = 'FUEL') 
     WHERE ML_ANOMALY_DETECTION.MLAD_METRIC = 'IFOREST_SCORE'
       AND ML_ANOMALY_DETECTION.DATETIME >= (CURRENT DATE - 9 DAYS) 
     ORDER BY DATETIME DESC)
AS FUEL_TEMP

I have tried JOIN, INNER JOIN, UNION/UNION ALL, but can't get it to work as it should. How can I do this?


Solution

  • Use a cross-join like this:

    create table table1 (field1 char(10));
    create table table2 (field2 char(10));
    create table table3 (field3 char(10));
    
    insert into table1 values('value1');
    insert into table2 values('value2');
    insert into table3 values('value3');
    
    select *
      from table1
      cross join table2
      cross join table3;
    

    Result:

    field1     field2     field3
    ---------- ---------- ----------
    value1     value2     value3
    

    A cross join joins all the rows on the left with all the rows on the right. You will end up with a product of rows (table1 rows x table2 rows x table3 rows). Since each table only has one row, you will get (1 x 1 x 1) = 1 row.