PGSQL使用sum重新获得请求

时间:2017-05-05 15:27:51

标签: sql postgresql recursive-query

我需要一些递归请求的帮助

递归选择:

WITH RECURSIVE r (child,name,qty) AS (

    SELECT l.item child, i.name as name, l.qty
    FROM items      
      LEFT JOIN lines l on i.bom = l.bom 

    UNION     

    SELECT d.child, d.name, d.qty 
    FROM (
       SELECT l.item child, i.name, l.qty
       FROM items i
         LEFT JOIN bom_lines l on i.bom = l.bom 
    ) as d
      JOIN r ON d.name = r.child
)
SELECT * FROM r;

但它不会计算数量的总数

1 个答案:

答案 0 :(得分:0)

 WITH RECURSIVE r (child,name,qty) AS (
     SELECT l.item child, i.name as name, l.qty
     FROM items i
     LEFT JOIN bom_lines l on i.bom = l.bom 
     UNION     
     SELECT d.child, d.name, d.qty+r.qty FROM (SELECT l.item child, i.name, l.qty
     FROM items i
     LEFT JOIN bom_lines l on i.bom = l.bom ) as d
     JOIN r
     ON d.name = r.child
 )
 SELECT * FROM r;