所有父子关系的数量乘以

时间:2014-11-25 21:52:50

标签: sql sql-server parent-child hierarchy

我有一张桌子。

======================================
ID  |  Description|Quantity| Parentid|
=====================================
1   |  Main       | NULL  | NULL   |
2   |  Sub        |  20   |  1     | 
3   |  Sub2       |  21   |  1     | 
4   |      A1     |  32   |  2     | 
5   |      B1     |  51   |  3     | 
6   |      B2     |  43   |  3     | 
7   |      C1     |  34   |  4     |
9   |      D1     |  22   |  5     |
10  |      D2     |  90   |  5     |
11  |      E1     |  21   |  7     |
12  |      F1     |  2    |  11    |
13  |      F2     |  42   |  11    |
14  |      G1     |  12   |  13    |
-------------------------------------

我想要G1的总量.G1的父亲是F2。 F2的父级是E1。 E1的父级是C1。 C1的父亲是A1。 A1的父亲是Sub。 Sub的父母是主要的。所以G1的总量是(12*42*21*34*32*20=230307840)

如何使用sql查询获得答案?

2 个答案:

答案 0 :(得分:0)

WITH TotalQuantity AS
(
    SELECT  Quantity, ParentID
    FROM    MyTable
    WHERE Description = 'G1'
    UNION ALL
    SELECT  TQ.Quantity * COALESCE(T.Quantity,1), T.ParentID
    FROM    TotalQuantity   TQ
    INNER JOIN MyTable      T   ON T.ID = TQ.ParentID
)

SELECT * FROM TotalQuantity
WHERE ParentID IS NULL

答案 1 :(得分:0)

这将为每一代提供增加的总数。

WITH Hierarchy(ChildId, Description, Quantity, Generation, ParentId)
AS
(
   SELECT Id, Description, Quantity, 0 as Generation, ParentId
        FROM Table1 AS FirtGeneration
        WHERE ParentId IS NULL        
   UNION ALL
   SELECT NextGeneration.Id, NextGeneration.Description,
          ISNULL(NextGeneration.Quantity, 1) * ISNULL(Parent.Quantity, 1), 
          Parent.Generation + 1, Parent.ChildId
   FROM Table1 AS NextGeneration
   INNER JOIN Hierarchy AS Parent ON NextGeneration.ParentId = Parent.ChildId    
)
SELECT *
FROM Hierarchy

仅限G1

select quantity from Hierarchy where description = 'G1' -- result = 230307840

SQL Fiddle