Tenho uma tabela assim:
-------------------------------------------------
| 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
---------------------------------------------------
Eu preciso gerar esse tipo de saída:
Radiology
-->Normal Radiology
-->Resonance
-->Cerebral Resonance with contrast
Lab Test
--> Blood Test
--> Calcium
Estou trabalhando no PostgreSQL. Eu tenho tentado isso com um CTE recursivo, mas não consegui gerar o que gosto:
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_list
FROM hierarchy
GROUP BY id, parent_list
ORDER BY parent_list;
Esse CTE recursivo produz a seguinte saída indesejável:
Radiology
Radiology--> Normal Radiology
Radiology--> Resonance
Radiology--> Resonance --> Cerebral Resonance with contrast
Lab Test
Lab Test --> Blood Test
Lab Test --> Calcium
Como eu posso fazer isso?