确定ORACLE COALESCE中使用的源

时间:2015-07-17 08:49:59

标签: sql oracle function coalesce

如何识别COALESCE为哪些来源返回数据?

我想要类似的东西:

SELECT    
COALESCE(SOURCE1, SOURCE2) SOURCE,
SOURCE_LOACTION
FROM
DATATABLE1 D1, DATATABLE2 D2

我在结果中有一列显示数据的来源

答案:

正如我惯常做的那样,并没有充分说出我的问题,所以我不得不用每个人提供的东西来弥补我的需求:

-- I was using COALESCE on more than one field
COALESCE(D1.FIELD1, D2.FIELD1) FIELD1,
COALESCE(D1.FIELD2, D2.FIELD2) FIELD2,
COALESCE(D1.FIELD3, D2.FIELD3) FIELD3,

CASE WHEN 

    D1.FIELD1 IS NULL AND
    D1.FIELD2 IS NULL AND
    D1.FIELD3 IS NULL AND

THEN 'SOURCE2' ELSE 'SOURCE1' END AS DATASOURCE

感谢您的帮助:)

2 个答案:

答案 0 :(得分:2)

我将如何做到这一点:

with sample_data as (select 1 id, 'a' source1, null source2 from dual union all
                     select 2 id, null source1, null source2 from dual union all
                     select 3 id, 'a' source1, 'b' source2 from dual union all
                     select 4 id, null source1, 'b' source2 from dual)
select id,
       coalesce(source1, source2) source,
       case when source1 is not null then 'source1' 
            else 'source2'
       end source_location1,
       case when source1 is not null then 'source1'
            when source2 is not null then 'source2'
       end source_location2
from   sample_data;


        ID SOURCE SOURCE_LOCATION1 SOURCE_LOCATION2
---------- ------ ---------------- ----------------
         1 a      source1          source1         
         2        source2                          
         3 a      source1          source1         
         4 b      source2          source2   

N.B。当source1和source2都为null时,我已经包含了两种处理大小写的方法;您选择哪一个取决于您在两个源都为null时显示的内容 - null或者在coalesce列表中提到的最后一个源。

答案 1 :(得分:2)

SELECT    
COALESCE(SOURCE1, SOURCE2) SOURCE,
,COALESCE(nvl2(source1,'source1',null), nvl2(source2,'source2',null)), 
FROM DATATABLE1 D1, DATATABLE2 D2