title: Sql Sum of child Items
body: <p>I need to add sum of child items to parent item. Child items 'childId' is same as parent item 'parentId'.</p>
  <p>In the below table the ParentId '45627' has total count 0. But, I need as 11. 11 is sum of child items totalcount.</p>
  <pre><code>+----------+---------+-------+------------+  
  | 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 |  
  +----------+---------+-------+------------+  
  </code></pre>
  <p>Expected output :</p>
  <pre><code>+----------+---------+-------+------------+  
  | 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 |  
  +----------+---------+-------+------------+ 
  </code></pre>
  <p>Though am able to achieve with self join but the performance is too slow.</p>
  <p>Is there any other way to get the expected output with better performance.</p>
  <p>The Query I have tried</p>
  <pre><code>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
  </code></pre>
  <p>Note: The above tables are examples. The records count can be 10,000.</p>