Oracle使用多种数据类型进行解包

时间:2017-04-27 02:15:05

标签: sql oracle unpivot

ID VT_Type1 Vt_type2 VT_Type3 Status_1 Status_2 Status_3 Date_1 Date_2 Date_3
 1       -1       -1        0 X        Y        2        04/12  05/12  06/12
 2       -1       -1       -1 A        B        1        06/12  07/12  07/10

预期输出

Id Type Status Date
1   1    X     04/12
1   2    Y     05/12
2   1    A     06/12
2   2    B     07/12
2   3    1     07/10

我可以通过引用此multiple case SQL query retrieve single row as multiple column中的答案来获得预期结果,但在我的表中,我引用的列具有不同的数据类型。就像VT_Type3是-1一样,我应该从Status_3读取数据,其中数字是其他2列是varchar2的数字。

1 个答案:

答案 0 :(得分:1)

使用子查询首先将Status_3列转换为与其他列相同的类型:

WITH test_data (
  ID,
  VT_Type1, Vt_type2, VT_Type3,
  Status_1, Status_2, Status_3, 
  Date_1, Date_2, Date_3
) AS (
       SELECT 1, -1, -1,  0, 'X', 'Y', 2, '04/12', '05/12', '06/12' FROM DUAL UNION ALL
       SELECT 2, -1, -1, -1, 'A', 'B', 1, '06/12', '07/12', '07/10' FROM DUAL
     )
SELECT  id, type, status, dt AS "DATE"
FROM    ( SELECT ID,
                 VT_Type1,
                 Vt_type2,
                 VT_Type3,
                 Status_1,
                 Status_2,
                 TO_CHAR( Status_3 ) AS status_3,
                 Date_1,
                 Date_2,
                 Date_3
          FROM   test_data
UNPIVOT ( (vt_type, status, dt)
          FOR type IN (
            ( vt_type1, status_1, date_1 ) as 1,
            ( vt_type2, status_2, date_2 ) as 2,
            ( vt_type3, status_3, date_3 ) as 3
          )
        )
WHERE   vt_type != 0;