Parent Query Listing in Oracle SQL

Viewed 20

wanted to list Parent and Child
data from single code column in table which contain Parent and Child in Same column one below the other

Code Description
4000 Agriculture Parent
4010 Crops Production Child
4011 Fishery Child
4100 Mining and Quarying Perents
4110 Non Metal Quarying Child
4111 Others Child

Result should be as below:

Code Description Result Column1 Result Column2
4000 Agriculture Agriculture
4010 Crops Production Crops Production
4011 Fishery Fishery
4100 Mining and Quarying Mining and Quarying
4110 Non Metal Quarying Non Metal Quarying
4111 Others Others

Need oracle SQL statement to list only parents in one column and respective Child in other column.

1 Answers

Assuming that your parents have a code that ends in 00 and children have a code that does not end in 00 with the same leading digits as the parent then you can use a hierarchical query:

SELECT code,
       description,
       CASE LEVEL WHEN 1 THEN description END AS result_column1,
       CASE LEVEL WHEN 2 THEN description END AS result_column2
FROM   table_name
WHERE  LEVEL <= 2
START WITH MOD(code, 100) = 0
CONNECT BY TRUNC(PRIOR code / 100) = TRUNC(code / 100)
AND        PRIOR code < code
ORDER SIBLINGS BY code

But you can probably simplify it to just:

SELECT code,
       description,
       CASE WHEN code LIKE '%00' THEN description END AS result_column1,
       CASE WHEN code NOT LIKE '%00' THEN description END AS result_column2
FROM   table_name
ORDER BY code;

Which, for the sample data:

CREATE TABLE table_name (Code, Description) AS
SELECT 4000, 'Agriculture'         FROM DUAL UNION ALL
SELECT 4010, 'Crops Production'    FROM DUAL UNION ALL
SELECT 4011, 'Fishery'             FROM DUAL UNION ALL
SELECT 4100, 'Mining and Quarying' FROM DUAL UNION ALL
SELECT 4110, 'Non Metal Quarying'  FROM DUAL UNION ALL
SELECT 4111, 'Others'              FROM DUAL;

Both output:

CODE DESCRIPTION RESULT_COLUMN1 RESULT_COLUMN2
4000 Agriculture Agriculture null
4010 Crops Production null Crops Production
4011 Fishery null Fishery
4100 Mining and Quarying Mining and Quarying null
4110 Non Metal Quarying null Non Metal Quarying
4111 Others null Others

fiddle

Related