在Oracle数据库中,我有一个表,其中包含许多不同测试类型的结果。
表:
object_tested, test_date, test_a, test_a_result, test_b, test_b_result
TmpObj timestamp, value1 value2 value3 value4
Run Code Online (Sandbox Code Playgroud)
我需要导出这些测试结果,但需要为每个测试创建一个单独的行,如下所示:
object_tested, test_date, test, test_result
TmpObj timestamp, value1, value2
TmpObj timestamp, value3, value4
Run Code Online (Sandbox Code Playgroud)
最快的方法是什么?也许是UNION或JOIN?
最简单的方法是union all:
select object_tested, test_date, test_a as test, test_a_result as test_result
from table t
union all
select object_tested, test_date, test_b as test, test_b_result as test_result
from table t;
Run Code Online (Sandbox Code Playgroud)
如果要在输出中使用测试类型:
select object_tested, test_date, 'a' as test_type, test_a as test, test_a_result as test_result
from table t
union all
select object_tested, test_date, 'b' as test_type, test_b as test, test_b_result as test_result
from table t;
Run Code Online (Sandbox Code Playgroud)
Oracle 11还支持unpivot执行类似操作的运算符。如果您有一个非常大的表并且在乎性能,unpivot或者使用方法join可以工作。