Oracle SQL - 从两列中选择并合并为一列

Jer*_*emy 3 sql oracle select

我有这张桌子:

Vals
Val1  Val2  Score
A     B     1 
C           2
      D     3
Run Code Online (Sandbox Code Playgroud)

我希望输出是一个单独的列,它是Vals1和Val2变量的"超集".它还保持与该值相关联的"得分"变量.

输出应该是:

Val Score
A   1
B   1
C   2
D   3
Run Code Online (Sandbox Code Playgroud)

从这个表中选择两次然后联合是绝对不可能的,因为生产它非常昂贵.另外,我不能使用with子句,因为此查询在子查询中使用了一个,并且由于某种原因,Oracle不支持两个with子句.

我真的不关心如何处理重复值,无论最简单/最快.

如何生成适当的输出?

dbe*_*ham 9

这是不使用unpivot的解决方案.

with columns as (
  select level as colNum from dual connect by level <= 2
),
results as (
  select case colNum
              when 1 then Val1
              when 2 then Val2
            end Val,
         score
    from vals,
         columns
)
select * from results where val is not null
Run Code Online (Sandbox Code Playgroud)

这里基本上是没有WITH子句的相同查询:

select case colNum
            when 1 then Val1
            when 2 then Val2
         end Val,
       score
  from vals,
       (select level as colNum from dual connect by level <= 2) columns
 where case colNum
            when 1 then Val1
            when 2 then Val2
         end is not null
Run Code Online (Sandbox Code Playgroud)

或者更简洁一些

select *
  from ( select case colNum
                     when 1 then Val1
                     when 2 then Val2
                  end Val,
                score
           from vals,
                (select level as colNum from dual connect by level <= 2) columns
        ) results
 where val is not null
Run Code Online (Sandbox Code Playgroud)