将行拆分为多行Oracle

时间:2014-10-13 16:50:54

标签: sql oracle

我有一个包含5列的表:ID,ERROR1,ERROR2,ERROR3,ERROR4。

小样本看起来像:

ID | Error 1 | Error 2 | Error 3 | Error 4 |
12 | YES     | (null)  |  (null) | YES |
15 |  (null) | YES     |  (null) | YES |

所以,我需要了解如何打破单行数据,其中有多列使用"是"并将其转换为具有相同ID的多个实例,并且只有一个列为该实例读取“是”。所以两条12条记录和两条15条记录,每条记录只有一个错误,剩下的就是任何一行。

谢谢

3 个答案:

答案 0 :(得分:3)

也许有帮助,但我不确定,如果我理解你的预期结果:

 SELECT ID, Error1, NULL AS Error2, NULL AS Error3, NULL AS Error4
   FROM table
  WHERE Error1 = 'YES'
  UNION
    ALL
 SELECT ID, NULL AS Error1, Error2, NULL AS Error3, NULL AS Error4
   FROM table
  WHERE Error2 = 'YES'
  UNION
    ALL
 SELECT ID, NULL AS Error1, NULL AS Error2, Error3, NULL AS Error4
   FROM table
  WHERE Error3 = 'YES'
   UNION
    ALL
 SELECT ID, NULL AS Error1, NULL AS Error2, NULL AS Error3, Error4
   FROM table
  WHERE Error4 = 'YES'

答案 1 :(得分:0)

作为替代解决方案,您可以将表格加入“diagonal matrix”,并在NULL不等于NULL的加入条款中获益:

SELECT T.ID, O.*
FROM T JOIN (
 --
 -- build a diagonal matrix
 --
 SELECT 'YES' as "Error 1", NULL as "Error 2", NULL as "Error 3", NULL as "Error 4"
  FROM DUAL
 UNION ALL SELECT NULL, 'YES', NULL, NULL
  FROM DUAL
 UNION ALL SELECT NULL, NULL, 'YES', NULL
  FROM DUAL
 UNION ALL SELECT NULL, NULL, NULL, 'YES'
  FROM DUAL
) O
ON T."Error 1" = O."Error 1"
OR T."Error 2" = O."Error 2"
OR T."Error 3" = O."Error 3"
OR T."Error 4" = O."Error 4";

请参阅http://sqlfiddle.com/#!4/bc0a7f/12

答案 2 :(得分:0)

我猜您正在寻找以下查询的输出

SELECT ID,
DECODE(COL_NUM,
    1, "ERROR 1",
    2, "ERROR 2",
    3, "ERROR 3",
    "ERROR 4") AS ERROR_COL
DECODE(COL_NUM,
        1, ERROR1,
        2, ERROR2,
        3, ERROR3,
        ERROR4) AS ERROR
FROM
TABLE,
(SELECT ROWNUM AS COL_NUM FROM DUAL WHERE ROWNUM<5)
WHERE
DECODE(COL_NUM,
        1, ERROR1,
        2, ERROR2,
        3, ERROR3,
        ERROR4) IS NOT NULL 

ID ---- ---- ERROR_COL ERROR

12 ----错误1 ------是

12 ----错误4 ------是

15 ----错误2 ------是

15 ----错误4 ------是