0

I have a table with 5 columns: ID, ERROR1, ERROR2, ERROR3, ERROR4.

A small sample would look like:

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

So, I need to understand how to break a single row of data where there are multiple columns with "Yes" and turn it into multiple instances of the same ID, and only a single column reading Yes for that instance. So two records of 12 and two records of 15, each having only one error and the rest Null for any individual row.

Thank you

3 Answers 3

3

Maybe that help, but I'm not sure, if I understand your expected result correctly:

 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'
Sign up to request clarification or add additional context in comments.

Comments

0

As an alternative solution, you could join your table on a "diagonal matrix", taking benefice in the join clause that NULL is not equal to 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";

See http://sqlfiddle.com/#!4/bc0a7f/12

Comments

0

I guess you are looking for the output for the following query

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----ERROR 1------YES

12----ERROR 4------YES

15----ERROR 2------YES

15----ERROR 4------YES

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.