I have a table where there are 4 columns namely :Book_no,Prev_Book_no(previous edition book_no),Edition_no(starts with 0 upto latest edition no(increments by 1)), Tree(Initially null).
What I intend to do is to create a tree of Book_no starting from highest edition to edition no 0.
Ex: (Book_no,Prev_Book_no,Edition_no) Values: (bbb,null,0), (ccc,bbb,1), (ddd,ccc,2), (eee,ddd,3), (fff,eee,4)
Then tree for every row should be:(bbb),(ccc,bbb),(ddd,ccc,bbb),(eee,ddd,ccc,bbb) and (fff,eee,ddd,ccc,bbb).
For this I tried using Recursive CTE with code as below:
with cte(book_no,prev_book_no,tree,edition_no) as
(select
book_no,prev_book_no,tree,edition_no
from books
where edition_no>=0
union all
select e.book_no,e.prev_book_no,concat(nvl(e.tree,''),','+e.prev_book_no),e.edition_no
from
cte e inner join books f
on e.prev_book_no=f.book_no
)
select distinct * from cte
order by edition_no;
But Redshift does not allow using cte table in from clause and gives the error. 'Table cte does not exist'.
P.S There are multiple different books in table.For example I have mentioned only one.
Is there any alternative to this in Redshift?
Edit:
Sample Data:
Expected Output:
Logic: I want to get a hierarchy of book no's and am using concat operation for the same.(Current code might be wrong) Thanks!