TSQL:从层次结构的顶部到底部的总和

时间:2016-02-23 18:49:50

标签: tsql recursive-query

我正在尝试针对多级层次结构进行某种运行总计。

样本表。我添加了空格来强调分组。

+----------------+----------------+------------+
|    Manager     |    Employee    |    Cost    |
+----------------+----------------+------------+
| Donald Torres  | Pamela Jordan  | 7,250.78   |
|                |                |            |
| Pamela Jordan  | Harry Rivera   | 36,721.39  |
| Pamela Jordan  | Ryan Mcdonald  | 5,593.89   |
|                |                |            |
| Harry Rivera   | Bruce Mccoy    | 3,538.19   |
|                |                |            |
| Ryan Mcdonald  | Shirley Ortiz  | 137.20     |
| Ryan Mcdonald  | Roger Gardner  | 9,140.34   |
| Ryan Mcdonald  | Paula Richards | 135,109.59 |
|                |                |            |
| Paula Richards | Andrew Boyd    | 106,676.77 |
+----------------+----------------+------------+

期望的输出

+----------------+----------------+------------+
|    Manager     |    Employee    |    Cost    |
+----------------+----------------+------------+
| Donald Torres  | Pamela Jordan  | 304,168.15 |
| Pamela Jordan  | Harry Rivera   | 40,259.58  |
| Pamela Jordan  | Ryan Mcdonald  | 256,657.79 |
| Harry Rivera   | Bruce Mccoy    | 3,538.19   |
| Ryan Mcdonald  | Shirley Ortiz  | 137.20     |
| Ryan Mcdonald  | Roger Gardner  | 9,140.34   |
| Ryan Mcdonald  | Paula Richards | 241,786.36 |
| Paula Richards | Andrew Boyd    | 106,676.77 |
+----------------+----------------+------------+

道歉,提供不正确的所需输出。我已经更新了表格。

基本上,这是基于初始表的层次结构的样子:

Donald Torres                   
    Pamela Jordan               7,250.78
        Harry Rivera            36,721.39
            Bruce Mccoy         3,538.19
        Ryan Mcdonald           5,593.89
            Shirley Ortiz       137.20
            Roger Gardner       9,140.34
            Paula Richards      135,109.59
                Andrew Boyd     106,676.77

关于所需的输出,Paula Richards应该得到Paula Richards(她的成本)和Andrew Boyd的总和。 Ryan Mcdonald将把Ryan Mcdonald(hir cost)的总和归功于Andrew Boyd。 Harry Rivera只会是Harry Rivera + Bruce Mccoy。最后,帕梅拉·乔丹将把帕梅拉·乔丹(她的成本)的总和归结为安德鲁·博伊德。

我正在尝试在SQL 2008R2中编写查询。

更新:添加cte基表

With Tabl_1 (Manager, Employee, Cost) as (
    Select 'Donald Torres'  , 'Pamela Jordan'  , 7250.78   UNION ALL
    Select 'Pamela Jordan'  , 'Harry Rivera'   , 36721.39  UNION ALL
    Select 'Pamela Jordan'  , 'Ryan Mcdonald'  , 5593.89   UNION ALL
    Select 'Harry Rivera'   , 'Bruce Mccoy'    , 3538.19   UNION ALL
    Select 'Ryan Mcdonald'  , 'Shirley Ortiz'  , 137.20     UNION ALL
    Select 'Ryan Mcdonald'  , 'Roger Gardner'  , 9140.34   UNION ALL
    Select 'Ryan Mcdonald'  , 'Paula Richards' , 135109.59 UNION ALL
    Select 'Paula Richards' , 'Andrew Boyd'    , 106676.77
)

1 个答案:

答案 0 :(得分:0)

我根据您的需要设计此查询。

-1