0

I have table company. It stores the following data: id, title, budget, pid (parent id), total amount. It is necessary to calculate the company's budget + budget of subsidiaries. I do it in the column total.

"SELECT o.id, o.title, o.budget, o.pid, 
(select sum(o1.budget)+o.budget from company o1 where o1.pid=o.id) total
FROM company o ORDER BY o.id"; 

This request summarizes the amount of budgets only on the level below, and I need to calculate the budgets of all the subordinate companies.

1 Answers1

0

You are missing a GROUP BY, without the GROUP BY you will only get the total sum of your budget, try something like this:

SELECT o.id, o.title, o.budget, o.pid, 
(select sum(o1.budget)+o.budget from company o1 where o1.pid=o.id) total
FROM company o 
GROUP BY o.id
ORDER BY o.id