I have a table like this:
table item
(
id int,
quantity float,
father int, -- refer to item itself in case of subitem
)
I need to sum al quantity plus sons quantity like this way:
select i.id, max(i.quantity)+sum(ft.quantity) as quantity
from item i
left join item ft on ft.id=i.id
group by i.id
My trouble is because relationship between father-son is recursive so I would like to sum also his grandfather quantity and so on… and i don’t know the maximum deepness, than I can not join many times.
What can i do?
Thank you.
You have to use a recursive CTE. Somthing like this:
SQL Fiddle Demo
This will give you something like: