Quantcast
Viewing all articles
Browse latest Browse all 75

Parent Child

I have a table that has a parentid and a childid (coa_cnf_account). I have another table that has the money associated with each of these accounts(rr_data_revenue). I am trying to get the parent total for what is in the parent account and all the accounts that are under that parent. I tried to write a CTE but I am missing something Here is what I got so far. ;WITH recurs AS ( SELECT coa_cnf_account.COAAccountId, coa_cnf_account.ParentAccountId, case when accountingtype = 1 then sum(RevenueAmount) else 0 end as Debit, case when accountingtype = 2 then sum(RevenueAmount) else 0 end as Credit FROM RR_DATA_REVENUE INNER JOIN coa_cnf_account on coa_cnf_account.COAAccountId = RR_DATA_REVENUE.coaaccountid -- WHERE ParentAccountId IS NOT NULL group by coa_cnf_account.COAAccountId, coa_cnf_account.ParentAccountId, accountingtype UNION ALL SELECT C.COAAccountId, C.ParentAccountId, R.Debit, r.Credit FROM RR_DATA_REVENUE INNER JOIN coa_cnf_account c on c.COAAccountId = RR_DATA_REVENUE.coaaccountid INNER JOIN recurs r ON r.ParentAccountid = c.COAAccountId ) SELECT R.COAAccountId, c.ParentAccountiD, c.Code, c.Name, sum(r.Debit) as Debit, sum(r.credit) as Credit, SUM(r.Debit - r.Credit) AS BAL FROM recurs R INNER JOIN coa_cnf_account c on c.COAAccountId = r.coaaccountid GROUP BY R.COAAccountId, c.Code, c.Name, c.ParentAccountiD ORDER BY COAAccountId, c.Code, c.Name Currently this returns me this ![alt text][1] I know that this is incorrect because I can do a sum on the amount for coaaccountid = 2 and it it 0 which is correct. It should have a total of 135.42 which is the sum of the 2 accounts under it. See this.. ![alt text][2] Any Help would be appreciated. [1]: /storage/temp/4485-question1.jpg [2]: /storage/temp/4486-2.jpg

Viewing all articles
Browse latest Browse all 75

Trending Articles