[英]Oracle left outer join issue
I'm having an issue in a reporting SQL with left outer join. 我在使用左外部联接的报表SQL中遇到问题。
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 表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 表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. 但是,仅当存在多于1行匹配且行中至少有一个满足两个条件时,才应应用左外部连接的最后两个条件
IS NOT NULL
和> 0
。 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. 您应该在左联接中不带条件的情况下运行查询,然后对条件进行判断,以从yyy表中确定值是否为空。
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. 在第8行,您应该对列进行别名处理,以便它们在上方的选择中区分开。 I named them aa_col1, yyy_col1, etc.
我将它们命名为aa_col1,yyy_col1等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.