PHP - 计算列hieararchy中的一些值

时间:2018-05-14 09:53:02

标签: php sql sql-server

我需要帮助来计算层次结构数组中的值。我有一张这样的桌子:

+--------+------------+-------+-----------+
| kia_id |  kia_name  | value | parent_id |
+--------+------------+-------+-----------+
|      1 | ac service |       |         0 |
|      2 | hil        |       |         0 |
|      3 | dispatch   |       |         1 |
|      4 | tat main   | 13.3  |         3 |
|      5 | tat air    | 10.1  |         3 |
|      6 | sla comp   | 11.7  |         2 |
|      7 | sla serv   |       |         2 |
|      8 | slb        | 9.9   |         7 |
+--------+------------+-------+-----------+

我想显示html那样的表:

+--------+----------------+-------+-----------+------------------------+
| kia_id |    kia_name    | value | parent_id | total_value_from_child |
+--------+----------------+-------+-----------+------------------------+
|      1 | ac service     |       |         0 | 23.4                   |
|      3 |    dispatch    |       |         1 | 23.4                   |
|      4 |       tat main | 13.3  |         3 |                        |
|      5 |       tat air  | 10.1  |         3 |                        |
|      2 | hil            |       |         0 | 21.6                   |
|      6 |    sla comp    | 11.7  |         2 |                        |
|      7 |    sla serv    |       |         2 | 9.9                    |
|      8 |       slb      | 9.9   |         7 |                        |
+--------+----------------+-------+-----------+------------------------+

如何计算所有子值以设置此父级的总数,请帮帮我..

1 个答案:

答案 0 :(得分:0)

我认为您需要将递归CTE与聚合相结合。我们的想法是从“底部”(叶子)开始,然后继续前进。然后汇总以引入原始数据。

with cte as (
      select kia_id, value, kia_id as parent_id, 0 as lev
      from t
      where not exists (select 1 from t t2 where t2.parent_id = t.kia_id)
      union all
      select cte.kia_id, cte.kia_value, t.parent_id, cte.lev + 1
      from cte join 
           t
           on cte.parent_id = t.kia_id
    )
select t.*, c.parent_value
from (select cte.parent_id, sum(kia_value) as parent_value
      from cte
      group by cte.parent_id
     ) c join
     t
     on t.kia_id = c.parent_id;