Total children values based on parent

时光毁灭记忆、已成空白 提交于 2019-12-02 23:47:13

问题


I have 2 tables: 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               

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=???

回答1:


Use a recursive 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



回答2:


It hurts my brain... The below should work for you, note that it is very rough and you will want to streamline it.

DECLARE @parent NCHAR(1), @child NCHAR(1), @runningTotal INT
SET @parent = 'a' -- set starting parent here
DECLARE myCursor CURSOR FOR SELECT [Parent], [Child], [Point] FROM table1 WHERE [Parent] = @parent
OPEN myCursor
FETCH NEXT FROM myCursor INTO @parent, @child, @runningTotal
WHILE @@FETCH_STATUS = 0
BEGIN
    IF EXISTS (SELECT * FROM table1 WHERE [Parent] = @child)
    BEGIN
        DECLARE @point INT
        SELECT @parent = [Parent], @child = [Child], @point = [Point] FROM table1 WHERE [Parent] = @child
        SET @runningTotal = @runningTotal + @point
    END
    ELSE
    BEGIN
        BREAK
    END
END
CLOSE myCursor
DEALLOCATE myCursor
SELECT @runningTotal


来源:https://stackoverflow.com/questions/24771646/total-children-values-based-on-parent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!