I need to add sum of child items to parent item. Child items 'childId' is same as parent item 'parentId'.
In the below table the ParentId '45627' has total count 0. But, I need as 11. 11 is sum of child items totalcount.
+----------+---------+-------+------------+
| ParentId | ChildId | Name | TotalCount |
+----------+---------+-------+------------+
| 45627 | 12568 | Test1 | 0 |
| 52678 | 45627 | Test2 | 0 |
| 23123 | 45627 | Test3 | 7 |
| 54312 | 45627 | Test4 | 3 |
| 32123 | 45627 | Test5 | 0 |
| 12111 | 45627 | Test6 | 1 |
| 32122 | 45627 | Test7 | 0 |
| 43123 | 45627 | Test8 | 0 |
+----------+---------+-------+------------+
Expected output :
+----------+---------+-------+------------+
| ParentId | ChildId | Name | TotalCount |
+----------+---------+-------+------------+
| 45627 | 12568 | Test1 | 11 |
| 52678 | 45627 | Test2 | 0 |
| 23123 | 45627 | Test3 | 7 |
| 54312 | 45627 | Test4 | 3 |
| 32123 | 45627 | Test5 | 0 |
| 12111 | 45627 | Test6 | 1 |
| 32122 | 45627 | Test7 | 0 |
| 43123 | 45627 | Test8 | 0 |
+----------+---------+-------+------------+
Though am able to achieve with self join but the performance is too slow.
Is there any other way to get the expected output with better performance.
The Query I have tried
SELECT a.parentId
,a.childId
,out1.TotalCount
FROM test a
LEFT JOIN (
SELECT a.parentId
,sum(b.TotalCount) AS TotalCount
FROM test a
INNER JOIN test b ON a.ParentId = b.childId
GROUP BY a.ParentId
) AS out1 ON a.ParentId = out1.ParentId
Note: The above tables are examples. The records count can be 10,000.