过滤Oracle查询结果表

时间:2019-11-20 15:03:48

标签: oracle

我有一个过程,其中有一个输入参数。我正在使用此参数过滤查询结果表。

procedure gettabledata(level in number, cur out sys_refcursor) is
begin
  open cur for
    with data as (
      select 'a' as field1, 'b' as field2, 'c' as field3, 'd' as field4, 10 as val from dual
      union all
      select 'a' as field1, 'b' as field2, 'd' as field3, 'c' as field4, 11 as val from dual
      union all
      select 'a' as field1, 'c' as field2, 'b' as field3, 'd' as field4, 12 as val from dual
      union all
      select 'a' as field1, 'c' as field2, 'd' as field3, 'b' as field4, 13 as val from dual
      union all
      select 'a' as field1, 'd' as field2, 'b' as field3, 'c' as field4, 14 as val from dual
      union all
      select 'a' as field1, 'd' as field2, 'c' as field3, 'b' as field4, 15 as val from dual
    )
    select null, null, null, field4, sum(val) from data where level = 1 group by field4
    union all
    select null, null, field3, field4, sum(val) from data where level = 2 group by field4, field3
    union all
    select null, field2, field3, field4, sum(val) from data where level = 3 group by field4, field3, field2
    union all
    select field1, field2, field3, field4, sum(val) from data where level = 4 group by field4, field3, field2, field1;
end;

工作正常,但我有一个疑问。是否有任何方法可以使用case when else语句来过滤结果表,或者不使用union语句?

1 个答案:

答案 0 :(得分:1)

是的。您可以按以下方式使用case when

select case when level = 4 then field1 end,
Case when level >= 3 then field2 end, 
case when level >= 2 then field3 end, 
field4, sum(val) from data
group by 
field4,
case when level >= 2 then field3 end,
Case when level >= 3 then field2 end
case when level = 4 then field1 end;

干杯!