troubleshooting Question

oracle: case when and subqueries linking 2 tables

Avatar of MarsM
MarsMFlag for United States of America asked on
Databases
3 Comments1 Solution346 ViewsLast Modified:
I have a problem with the case...when... statement from oracle.

I have 2 tables:
TABLE A:
ID_NUMBER,
TITLE

TABLE B:
ID_NUMBER_CHILD,
ID_NUMBER_PARENT

Cases can be parents, childs or single (no parent/child relationship in table B)
Child cases have no TITLE in Table A.

I want the following output:
ID_NUMBER
ID_NUMBER_PARENT (if exists else '-')
TITLE (from parent if it is a child otherwise straight from table A)

I can't change the data in the tables so I tried something like this:
SELECT
      ID_NUMBER,
      CASE ID_NUMBER
            WHEN (SELECT ID_NUMBER_PARENT FROM B WHERE ID_NUMBER_CHILD = A.ID_NUMBER)
            THEN (SELECT ID_NUMBER_PARENT FROM B WHERE ID_NUMBER_CHILD = A.ID_NUMBER)
            ELSE '-'
            END,
      CASE ID_NUMBER
            WHEN (SELECT ID_NUMBER_PARENT FROM B WHERE ID_NUMBER_CHILD = A.ID_NUMBER)
            THEN (SELECT A.TITLE FROM A WHERE A.ID_NUMBER = (SELECT ID_NUMBER_PARENT FROM B WHERE
            ID_NUMBER_CHILD = A.ID_NUMBER))
            ELSE A.TITLE
            END
      FROM A

Obviously the 3rd column doesn't give the correct output because A.ID_NUMBER in the THEN-part is not the 'overall' ID_NUMBER but the ID_NUMBER from the subquery.
I've tried an alias for the first column and use this in the caase statement. This didn't work.
Any suggestions to get the 3rd column correct?

Regards, Marcel
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 3 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 3 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros