如果当前行中的列为空,如何从不同的行中选择值?

时间:2016-05-11 16:54:35

标签: sql oracle

我的select SQL中有一个解码语句,如下所示 -

...
decode(instr(col1,'str1'), 0, 'STR1', 'STR2') as NAME,
...

问题是col1可能为null。所以我想我可以使用如下的内部解码 -

decode(instr(
  decode(col1, null, (
    select unique col1 from SAMETABLE st where st.pid = pid) as col2, col1), 'str1'), 0, 'STR1', 'STR2') as NAME,

但它失败了。

以下是DB中可能的快照 -

      col1       pid
row1  null       1
row2  somevalue  1

我想在row1中使用col1的值来替换row1中的值,当row1中的col1为空时,将两个记录替换为' pid是平等的。

任何人都可以指出我是否做了不可能的事情?

2 个答案:

答案 0 :(得分:1)

您的代码存在以下问题:

  • 您为内部表格提供了别名st,然后执行where st.pid = pid,但这是一个自我引用,因为另一个pid也来自于内部查询。相反,请在主查询中为别名提供别名。

  • 您将内部查询的结果赋予别名(as col2),但在表达式中不允许使用别名,因此需要将其删除。

  • 内部查询选择unique col1,但仍然可以提供多个结果,这会产生错误。内部查询必须始终返回一个值(当存在不同的非空值时,即使没有,也是如此)。因此,您应该使用聚合函数,例如min

  • decode(a, null, b, a)还有很长的路要走nvl(a, b)

所以你可以使用它:

select decode(
      instr(
        nvl(col1, (select min(col1) from t where pid = t1.pid)),
        'str1'
      ), 
      0, 'STR1', 'STR2'
    ) as NAME
from mytable t1

答案 1 :(得分:0)

我在Oracle 11 g中尝试了这个,它运行得很好。我也试图改变col1的起始值,它的工作原理。所以我猜你还有一些与字段类型有关的问题,而不是DECODE的工作方式。

    DECLARE
    col1   VARCHAR(10);
    result VARCHAR2(10);
    BEGIN
      col1:=null;
        select DECODE(
                 instr(DECODE(col1, null, (select 'HELLO' from DUAL),
                              col1),'str1'), 0, 'STR1', 'STR2') into result  
        from  DUAL;
        dbms_output.PUT_LINE(result);

     END

我猜你必须改变子查询:

select unique col1 from SAMETABLE st where st.pid = pid

类似

select unique col1 from SAMETABLE st where st.pid = pid and col1 is not null
相关问题