Reputation: 15
I get a table looking like this:
If the id doesn't get a parent, I need to get "created_at" of it and if he got one, I need to get the "created_at" of the last parent. I tried left join, without success.
Expected results are:
Upvotes: 0
Views: 38
Reputation: 439
Try this:
WITH RECURSIVE tree(id, created_at, parent_id) AS (
SELECT id, created_at, parent_id
FROM your_table
WHERE parent_id IS NULL
UNION ALL
SELECT
c.id,
p.created_at,
c.parent_id
FROM tree AS p, your_table AS c
WHERE c.parent_id = p.id
)
SELECT * FROM tree AS n
Look up at this fiddle: https://www.db-fiddle.com/f/xyqSDNapZBm6zd3eZ4wauo/1
Upvotes: 1