sqloracle-databasesubquery-factoring

Use result of select query into another multiple times


I have one complex select query(Query-1) which is executed using INTERSECT and it returns IDs of a particular column.

Query #1:

SELECT my_id FROM my_table
INTERSECT
SELECT my_id FROM other_table;

Now there is another more complex query which requires the result from query #1 multiple times.

Query #2:

SELECT * 
FROM
    (SELECT my_id, col_1, my_value
     FROM my_table
     WHERE my_id IN (result from query-1) 
       AND col_3 IN (SELECT col_3 FROM another_table1 
                     WHERE my_id IN (result from query-1) 
                       AND another_col IN (SELECT another_col 
                                           FROM another_table2 
                                           WHERE my_id IN (result from query-1))))
    PIVOT 
        (MIN(my_value)
            FOR(col_1) IN(1 AS name, 2 AS lastname, 3 AS address)
        )

As you can see results from query-1 is required multiple times in query-2, what I tried is to substitute entire query-1 in query-2 wherever needed which increases complexity and readability of the query.

Is there a way to do this in simple manner?


Solution

  • how about using the with clause (subquery factoring clause):

    with query-1 as (SELECT my_id FROM my_table
    INTERSECT
    SELECT my_id FROM other_table)
    
    SELECT * FROM
    (
       SELECT my_id, col_1, my_value
       FROM my_table
       WHERE my_id IN (select id from query-1) AND col_3 IN
          (SELECT col_3 FROM another_table1 WHERE my_id IN (select id from query-1) AND another_col IN
             (SELECT another_col FROM another_table2 WHERE my_id IN (select id from query-1))
    )
    )
    PIVOT (
       MIN(my_value)
       FOR(col_1)
       IN(1 AS name, 2 AS lastname, 3 AS address)
    )