基于父母的子女孩总值

时间:2014-07-16 03:18:29

标签: sql postgresql common-table-expression recursive-query

我有两张桌子:table1table2

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中父项的子项积分的总和。

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

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

UPDATE table2 set Total=???

2 个答案:

答案 0 :(得分:2)

使用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

答案 1 :(得分:0)

它伤害了我的大脑...下面应该适合你,请注意它非常粗糙,你会想要简化它。

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