I have a table like this:
-------------------------------------------------| id | description | parent_id | cost--------------------------------------------------| 1 | Radiology | NULL | 0.00| 2 | Lab Tests | NULL | 0.00| 3 | Normal Radiology | 1 | 0.00| 4 | Resonance | 1 | 100.00| 1100 | Cerebral Resonance| 4 | 200.00| 1900 | Blood Tests | 2 | 10.00| 2044 | Calcium | 2 | 50.00---------------------------------------------------
I need to generate this kind of output:
Radiology -->Normal Radiology -->Resonance -->Cerebral Resonance with contrastLab Test --> Blood Test --> Calcium
I'm working on PostgreSQL. I've been trying this with a recursive CTE, but I was unable to generate what I like:
WITH RECURSIVE hierarchy AS ( SELECT id, CAST(description AS TEXT) AS parent_list FROM orders WHERE parent_id is null UNION SELECT c.id, CAST(c2.parent_list || ' --> ' || c.description as text) as parent_list FROM orders c INNER JOIN hierarchy c2 ON c.parent_id = c2.id )SELECT id, parent_listFROM hierarchyGROUP BY id, parent_listORDER BY parent_list;
That recursive CTE produces the following nondesirable output:
RadiologyRadiology--> Normal RadiologyRadiology--> ResonanceRadiology--> Resonance --> Cerebral Resonance with contrastLab TestLab Test --> Blood TestLab Test --> Calcium
How can I do it?