'How to merge sum of child value to parent in same sqlite table

I have two sql table named ledger and chart of account

Ledger table as below

-----------------------------------------------------------------
| id  | Acc_Category  |           name         | Credit | Debit  |
|-----|---------------|------------------------|--------|--------|
|  1  |      6        | Bank Charge paid       |   100  |   0    |
|  2  |     13        | Membership fee rec.    |   0    |  1500  |  
|  3  |     11        | Pettycash Account rec  |  2580  |   0    |
|  4  |     12        | Other rent rec         |   0    | 2000   |
|  5  |     10        | Membership fee rec     |   0    | 1500   |    
------------------------------------------------------------------

Chart of account table as below (this table is dynamic, end user can add or modify child and parent, it is hierarchy nested table

----------------------------------------------------
| id  | Parent_ID |         name           |balance |  
|-----|-----------|------------------------|--------|
|  1  |    0      | Profit & Loss Account  |  [sum] | (sum of child)  
|  2  |    0      | Balance Sheet          |  [sum] | (sum of child)
|  3  |    1      | Expense                |  [sum] | (sum of child)
|  5  |    2      | Assets                 |  [sum] | (sum of child)
|  6  |    3      | Other Expense          |  100   | (sum of child)
|  7  |    1      | Income                 |  [sum] | (sum of child)
|  8  |    5      | Cash                   |  [sum] | (sum of child)
|  9  |    6      | Interest Expense       |    0   | 
| 10  |    7      | Revenue                |  [sum] | (sum of child)
| 11  |    8      | Pettycash Account      |   2580 | 
| 12  |   10      | Other rent received    |   2000 | 
| 13  |   10      | Membership fee         |   3000 |  
----------------------------------------------------

i want get total amount of each children to parent balance column.. any one can help me to get total amount of parent

i have tried with below query

WITH w1( id, parentId, name, balance, level) AS  
    (    SELECT  id, Parent_ID, Category_Name,
       (SELECT SUM("Ledger"."Debit" - "Ledger"."Credit")  FROM  "Ledger" WHERE  "Ledger"."Acc_Category" = account_category.id ) as balance,
            0 AS level  FROM  account_category  WHERE "Balance" not NULL                   
        UNION  SELECT account_category.id, account_category."Parent_ID", account_category."Category_Name" ,0, level + 1
          FROM account_category  JOIN w1 ON account_category.id= w1.parentId     
     )  SELECT *,
      CASE
       WHEN  level != 0 then  (select sum(balance) as balance from w1 where id = parentId) 
     else balance
     END as abc
      FROM w1 order by level desc;

but no luck

Thanks in advance



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source