【问题标题】:Total children values based on parent基于父级的总子级值
【发布时间】:2014-07-16 03:18:28
【问题描述】:

我有 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 中父级的子级积分之和。

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

我试了很多次都搞不明白。

UPDATE table2 set Total=???

【问题讨论】:

  • “基于孩子和父母”到底是什么意思?
  • 基于child的点总和。例如table2中a的总和为1050
  • Table2 有你的结果。但是您如何根据 table1 计算总和?在表1中,a只有一个孩子100分
  • 结果是根据父母有多少个孩子和所有的总和。例如,a总共有4个孩子,分别是b、c、d、e,但级别不同。

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


【解决方案1】:

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

    它伤了我的大脑......下面应该适合你,注意它很粗糙,你会想要精简它。

    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
    

    【讨论】:

    • 这对 Postgres 无效
    • 我没有注意问题标签,只用SQL Server测试过,对于其他数据库系统,它需要一些改变——只是解决问题的一个想法。
    • 即使在 SQL Server 中,这也是一个低效的解决方案(因为 SQL Server 也支持递归查询。基于游标的方法总是比基于集合的方法慢)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 2019-02-03
    相关资源
    最近更新 更多