2011-05-25 55 views
1

我該如何去做這樣的交叉表查詢?交叉表查詢與類別總計,樹表結構

 TopItem1 TopItem2 Category1 Ca1Item1 Ca1Item2 Category2 Ca2Sub1 Ca2Sub1It1 Ca2Sub1It2 Ca2Sub2 Ca2Sub2It1 
Group1  1  3  6   2  4  4   3  1   2   1  1 
Group2  3  1  0   0  0  5   4  2   2   1  1 

即具有每個類別的總計的交叉表查詢。與列標題

的樹狀結構表是這樣的:

tSource

Key Value  Parent 
1 TopItem1 
2 TopItem2 
3 Category1 
4 Category2 
5 Ca1Item1 3 
6 Ca1Item2 3 
7 Ca2Sub1  4 
8 Ca2Sub2  4 
9 Ca2Sub1It1 7 
10 Ca2Sub1It2 7 
11 Ca2Sub2It1 8 

與行標題和值進行計數表,你會希望他們是什麼。

現在我知道完全不可能創建適用於樹的任意深度的查詢,但如果我只有3個級別顯示,我如何獲得交叉表查詢以顯示類別總數?

回答

0

對於相對較淺的「樹深度」,您可以使用自聯接的聯合來將子記錄的金額與其父母和祖父母的金額相匹配。例如,與表名爲[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