對於相對較淺的「樹深度」,您可以使用自聯接的聯合來將子記錄的金額與其父母和祖父母的金額相匹配。例如,與表名爲[TBL含有
Key Value Parent Amount GroupName
--- ---------- ------ ------ ---------
1 TopItem1 5 Group1
2 TopItem2 6 Group1
3 Category1 7 Group1
4 Category2 8 Group1
5 Ca1Item1 3 20 Group1
6 Ca1Item2 3 40 Group1
7 Ca2Sub1 4 60 Group1
8 Ca2Sub2 4 80 Group1
9 Ca2Sub1It1 7 400 Group1
10 Ca2Sub1It2 7 500 Group1
11 Ca2Sub2It1 8 600 Group1
查詢
SELECT t.Value, t.Amount, t.GroupName FROM tbl t
UNION ALL
SELECT t2.Value, t1.Amount, t1.GroupName
FROM
tbl t1
INNER JOIN
tbl t2
ON t1.Parent = t2.Key
UNION ALL
SELECT t3.Value, t1.Amount, t1.GroupName
FROM
(
tbl t1
INNER JOIN
tbl t2
ON t1.Parent = t2.Key
)
INNER JOIN
tbl t3
ON t2.Parent = t3.Key
將返回
- 量爲每個 「值」 本身,
- 的量每個「Value」的子記錄以及每個「Val」的孫子記錄的金額UE」
生產
Value Amount GroupName
---------- ------ ---------
TopItem1 5 Group1
TopItem2 6 Group1
Category1 7 Group1
Category2 8 Group1
Ca1Item1 20 Group1
Ca1Item2 40 Group1
Ca2Sub1 60 Group1
Ca2Sub2 80 Group1
Ca2Sub1It1 400 Group1
Ca2Sub1It2 500 Group1
Ca2Sub2It1 600 Group1
Category1 20 Group1
Category1 40 Group1
Category2 60 Group1
Category2 80 Group1
Ca2Sub1 400 Group1
Ca2Sub1 500 Group1
Ca2Sub2 600 Group1
Category2 400 Group1
Category2 500 Group1
Category2 600 Group1
所以如果我們總結,在交叉表查詢
TRANSFORM Sum([Amount]) AS whatever
SELECT [GroupName]
FROM
(
SELECT t.Value, t.Amount, t.GroupName FROM tbl t
UNION ALL
SELECT t2.Value, t1.Amount, t1.GroupName
FROM
tbl t1
INNER JOIN
tbl t2
ON t1.Parent = t2.Key
UNION ALL
SELECT t3.Value, t1.Amount, t1.GroupName
FROM
(
tbl t1
INNER JOIN
tbl t2
ON t1.Parent = t2.Key
)
INNER JOIN
tbl t3
ON t2.Parent = t3.Key
)
GROUP BY [GroupName]
PIVOT [Value]
我們得到
GroupName Ca1Item1 Ca1Item2 Ca2Sub1 Ca2Sub1It1 Ca2Sub1It2 Ca2Sub2 Ca2Sub2It1 Category1 Category2 TopItem1 TopItem2
--------- -------- -------- ------- ---------- ---------- ------- ---------- --------- --------- -------- --------
Group1 20 40 960 400 500 680 600 67 1648 5 6