I have a complex query ((Q1 union Q2) intersect (Q3 union Q4)). Now the issue is one of the column involved in the queries has the value of 'Company'. This value can be a particular company name or a value of 'ALL' which means all companies. I have a separate company table which lists the company names. Now the logic is if one of the query in intersect has a value of 'ALL' and the other query is company 'C1', the result should return 'C1'. But currently since 'ALL' does not match 'C1' as a string value the intersect does not return anything. Is there anyway I can replace the 'ALL' row value with all the company names and then do the intersect? I want to do all the operations through SQL because handling it in code will be very cumbersome. I am using DashDB which is based on DB2.
This is the query that solved my issue (I have removed complexities from the query and only included those portions related to this question)
SELECT
AA.OBJECT_TYPE,
AA.OBJECT_FILTER_ID,
CASE WHEN BB.OBJECT_FILTER_VALUE = 'ALL'
THEN AA.OBJECT_FILTER_VALUE
ELSE BB.OBJECT_FILTER_VALUE
END AS OBJECT_FILTER_VALUE FROM
(
SELECT
OBJECT_TYPE,
OBJECT_FILTER_ID,
OBJECT_FILTER_VALUE
from COMPANY
) AS AA
INNER JOIN
(
SELECT
OBJECT_TYPE ,
OBJECT_FILTER_ID ,
OBJECT_FILTER_VALUE
FROM DETAILS
) AS BB
ON
AA.OBJECT_TYPE = BB.OBJECT_TYPE AND
AA.OBJECT_FILTER_ID = BB.OBJECT_FILTER_ID AND
(
AA.OBJECT_FILTER_VALUE = BB.OBJECT_FILTER_VALUE OR
AA.OBJECT_FILTER_VALUE = 'ALL' OR
BB.OBJECT_FILTER_VALUE = 'ALL'
)