将行拆分为多行 Oracle
Posted
技术标签:
【中文标题】将行拆分为多行 Oracle【英文标题】:Split row into multiple rows Oracle 【发布时间】:2014-10-13 16:50:53 【问题描述】:我有一个包含 5 列的表:ID、ERROR1、ERROR2、ERROR3、ERROR4。
一个小样本看起来像:
身份证 |错误 1 |错误 2 |错误 3 |错误 4 | 12 |是 | (空) | (空) |是 | 15 | (空) |是 | (空) |是 |因此,我需要了解如何在有多列“是”的情况下拆分单行数据,并将其转换为具有相同 ID 的多个实例,并且该实例只有一列读取“是”。因此,两条记录 12 和两条记录 15,每条记录只有一个错误,其余为 Null 用于任何单独的行。
谢谢
【问题讨论】:
【参考方案1】:也许这有帮助,但我不确定我是否正确理解了您的预期结果:
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'
【讨论】:
【参考方案2】:作为替代解决方案,您可以在“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
【讨论】:
【参考方案3】:我猜你正在寻找以下查询的输出
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----错误
12----错误1-----是
12----错误 4-----是
15----错误2-----是
15----错误 4-----是
【讨论】:
以上是关于将行拆分为多行 Oracle的主要内容,如果未能解决你的问题,请参考以下文章