基于父级的子级值总计 [英] Total children values based on parent

查看:74
本文介绍了基于父级的子级值总计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个表: table1 table2

Parent  Child  Point            Parent     Total
a       b       100               a          0(default)   (result = 1050)
b       c       200               b          0            (result = 950)
c       d       250               c          0            (result = 750)
d       e       500               

table2中的结果应该是 table1 中基于父项的子项总和。

The result in table2 should be sum of the children points based on parent in table1.

a---b---c---d---e

我尝试了很多次,但无法弄清楚。

I tried many times but cant figure out.

UPDATE table2 set Total=???


推荐答案

使用递归CTE

WITH RECURSIVE cte AS (
   SELECT parent, child, point AS total
   FROM   tbl1

   UNION ALL
   SELECT c.parent, t.child, c.total + t.point
   FROM   cte  c
   JOIN   tbl1 t ON t.parent = c.child
   )
SELECT *
FROM   cte

这篇关于基于父级的子级值总计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆