I'm having an issue in a reporting SQL with left outer join.
SELECT * FROM xx.aa
LEFT OUTER JOIN xx.yyy
ON aa.some_column_1 = yyy.some_column_1
AND aa.some_column_2 = yyy.some_column_2
AND aa.some_column_3 = yyy.some_column_3
AND yyy.some_year = '2015'
AND yyy.some_column_4 IS NOT NULL
AND yyy.some_column_4 > 0
WHERE aa.some_column_1 = '1234'
AND aa.some_column_2 = 'SOME_VALUE'
AND aa.end_date >= TO_DATE('01-JAN-2015','DD-MON-YYYY')
AND aa.start_date <= TO_DATE('31-DEC-2015','DD-MON-YYYY')
AND (aa.some_column_3 = 'SOME_VALUE')
Table aa
some_column_1 some_column_2 some_column_3 start_date end_date
1234 SOME_VALUE SOME_VALUE 1/1/2011 6/30/2014
1234 SOME_VALUE SOME_VALUE 7/1/2014 6/30/2015
Table yyy
some_column_1 some_column_2 some_column_3 some_column_4 some_year
1234 SOME_VALUE SOME_VALUE 444 2015
However, the last two conditions in the left outer join, IS NOT NULL
and > 0
, should ONLY be applied when there is MORE THAN 1 ROW MATCHED and if AT LEAST one of the rows satisfies both conditions. Else it will be a problem.
Any ideas?
You should run the query without the condition in the left join, then do a discution about your conditions to decide the values from yyy table if they are null or not.
select aa_col1, aa_col2, ..., aa_coln,
case when cnt > 2 and cond > 1
and not (yyy_some_column_4 IS NOT NULL AND yyy_some_column_4 > 0)
then null else yyy_col1
end as yyy_col1,
,...the other columns of yyy
from(
SELECT aa.*, yyy.*,
count(*) over() as cnt,
count(case when yyy.some_column_4 IS NOT NULL AND yyy.some_column_4 > 0 then 1 end) over() as cond
FROM xx.aa
LEFT OUTER JOIN xx.yyy
ON aa.some_column_1 = yyy.some_column_1
AND aa.some_column_2 = yyy.some_column_2
AND aa.some_column_3 = yyy.some_column_3
AND yyy.some_year = '2015'
WHERE aa.some_column_1 = '1234'
AND aa.some_column_2 = 'SOME_VALUE'
AND aa.end_date >= TO_DATE('01-JAN-2015','DD-MON-YYYY')
AND aa.start_date <= TO_DATE('31-DEC-2015','DD-MON-YYYY')
AND (aa.some_column_3 = 'SOME_VALUE')
)
At line 8 you should alias the columns so they be distinct in the upper select. I named them aa_col1, yyy_col1, etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.