I would appreciate any help on how to get totals of a parents and its children. I have two tables Units and UnitValues, one has parent child relation, and the second has only child and parent ids with associated values. I need to get a table that calculates total for a given parent and all its children.
I tried the following
;WITH tbl AS(
SELECT ParentUnit,
Sum(Value) AS Population,
Sum(CASE WHEN Mark IN ('A','B') THEN Value ELSE 0 END) AS Mark
FROM [TestDB].[dbo].[UnitValues] uv
INNER JOIN [TestDB].[dbo].[Units] u
On u.UnitID = uv.UnitID
Group By ParentUnit
)
select *
from tbl
where ParentUnit IN ('1TTTTT','2KKKKK')
It gives the incorrect result. The counts should be 6 instead of 2 for 2KKKKK, and 15 instead of 9 for 1TTTTT.
+--------+-------------------+--------+
| Unit | Population | Mark |
+--------+-------------------+--------+
| 1TTTTT | 9 | 9 |
| 2KKKKK | 2 | 2 |
+--------+-------------------+--------+
Units table
+--------+----------+------------+
| UnitID | Name | ParentUnit |
+--------+----------+------------+
| 1TTTTT | Unit | NULL |
| 2KKKKK | Unit 1 | 1TTTTT |
| 2LLLLL | Unit 2 | 1TTTTT |
| 2NNNNN | Unit 3 | 1TTTTT |
| 3KKKKG | Unit 1.2 | 2KKKKK |
| 3KKKKS | Unit 1.1 | 2KKKKK |
| 3LLLLL | Unit 2.1 | 2LLLLL |
| 4LLLLL | Unit 2.2 | 3LLLLL |
| 5LLLLL | Unit 2.3 | 4LLLLL |
+--------+----------+------------+
UnitValues table
+-----+--------+---------+-------+------+
| ID | UnitID | OtherId | Value | Mark |
+-----+--------+---------+-------+------+
| T12 | 1TTTTT | GGGGGG | 1 | |
| T22 | 2KKKKK | RRRRRR | 1 | A |
| T23 | 2KKKKK | RRRRRR | 1 | A |
| T24 | 2KKKKK | RRRRRR | 1 | B |
| T25 | 2KKKKK | RRRRRR | 1 | A |
| T31 | 2LLLLL | HHHHHH | 1 | A |
| T32 | 2LLLLL | HHHHHH | 1 | A |
| T33 | 2LLLLL | HHHHHH | 1 | B |
| T41 | 2NNNNN | HHHHHH | 1 | A |
| T42 | 2NNNNN | HHHHHH | 1 | A |
| T51 | 3KKKKG | BBBBBB | 1 | A |
| T52 | 3KKKKS | BBBBBB | 1 | A |
| T61 | 3LLLLL | BBBBBB | 1 | A |
| T71 | 4LLLLL | BBBBBB | 1 | A |
| T81 | 5LLLLL | BBBBBB | 1 | A |
+-----+--------+---------+-------+------+