Received: from malur.postgresql.org ([2a02:16a8:dc51::56]) by arkaria.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1fVNsY-0006Mh-A3 for pgsql-general@arkaria.postgresql.org; Tue, 19 Jun 2018 21:09:30 +0000 Received: from localhost ([127.0.0.1] helo=malur.postgresql.org) by malur.postgresql.org with esmtp (Exim 4.89) (envelope-from ) id 1fVNsX-00079Y-2n for pgsql-general@arkaria.postgresql.org; Tue, 19 Jun 2018 21:09:29 +0000 Received: from magus.postgresql.org ([2a02:c0:301:0:ffff::29]) by malur.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA384:256) (Exim 4.89) (envelope-from ) id 1fVNoc-0000P2-P3 for pgsql-general@lists.postgresql.org; Tue, 19 Jun 2018 21:05:26 +0000 Received: from mail-wm0-x232.google.com ([2a00:1450:400c:c09::232]) by magus.postgresql.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_CBC_SHA1:256) (Exim 4.89) (envelope-from ) id 1fVNoZ-00053M-GA for pgsql-general@postgresql.org; Tue, 19 Jun 2018 21:05:25 +0000 Received: by mail-wm0-x232.google.com with SMTP id v131-v6so2947634wma.1 for ; Tue, 19 Jun 2018 14:05:22 -0700 (PDT) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20161025; h=mime-version:subject:from:in-reply-to:date:cc :content-transfer-encoding:message-id:references:to; bh=cNcUWDBAkLtm/85KwDnfr02YVVQEfCnehMzv1eoe4mc=; b=NkdsyDJ2Zrpkpf4qJft4LQLLqCEQs970onD/est9RsAY39pVtgT/2Q5GgLOyXVziNo vUPaybxQ4geHKDwBEbnQuGgrb8TUO3kb+FZoUrZysvjp0B2JHiUD0lvqOqkctJvQekl+ lgKpk+Ucl+rjl7GRvW1nVzKiIbE29ozRIhQZC4AMJgAuoowbExXrww4hihMvPQRye5eK 2xHZoh6Cc5S3tM1NmLworWOnpaCyQpahlZPKf+4YburvE6FefTX0azh1oiiAINPd2RKT mQe3uvy4oXde7H+PNNcb28/NZiMXi1nE5wpVrK9zaOJ/CJJSUFky2sN1mB88XPLQPHa4 vyWA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20161025; h=x-gm-message-state:mime-version:subject:from:in-reply-to:date:cc :content-transfer-encoding:message-id:references:to; bh=cNcUWDBAkLtm/85KwDnfr02YVVQEfCnehMzv1eoe4mc=; b=L9HObqqBqetqHOVkrIhdJ+t3OR6g5D4WoBqHgrny8PZ9b24YpxvfhMmFq3EKa5gD9j y5/4vFawmI35Qnlr+Yr0E6pIg2DWISj+qYc05gvGRCVXZZQFfYceDMrEIo0V1V6+PY9U T6kjoXCzzTat77Wb3E59ejERExSxY7xWEjzRMnnQV2acBUPxFtqZSif9rvWlXUsXs8NA He0wG1U1B+/TTgt/Z27/TSTGrK1PkaKsbUWfsOWBD4oyTULLJ9yWEWiWIK5R8k3CV/Z2 CyT82/kpvxucnVAPOsubaVksV+kCFvmxgRouAbEyOmxwG6H/nUCQ9D5vgTLeHJYr2rWQ dqtA== X-Gm-Message-State: APt69E15u6zPE6zg5mzLzgzabMHe5M3qe0Xu7SH85xhLFBQdmbWSxURQ vJ+DKuWoLzGomoFgbPSJ4B0= X-Google-Smtp-Source: ADUXVKI6urPqfnQHAcncAQDzzIoDfLGN1B1RihTsNck6NwOItgTk0n2QvSkPwclMJzlCO+1b9OdRKw== X-Received: by 2002:a50:b761:: with SMTP id g88-v6mr15947848ede.129.1529442322109; Tue, 19 Jun 2018 14:05:22 -0700 (PDT) Received: from hollewijn.internal (84-245-13-9.dsl.cambrium.nl. [84.245.13.9]) by smtp.gmail.com with ESMTPSA id y22-v6sm336222edm.95.2018.06.19.14.05.21 (version=TLS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128); Tue, 19 Jun 2018 14:05:21 -0700 (PDT) Content-Type: text/plain; charset=utf-8 Mime-Version: 1.0 (Mac OS X Mail 11.4 \(3445.8.2\)) Subject: Re: Is postorder tree traversal possible with recursive CTE's? From: Alban Hertroys In-Reply-To: Date: Tue, 19 Jun 2018 23:05:19 +0200 Cc: "pgsql-general@postgresql.org" Content-Transfer-Encoding: quoted-printable Message-Id: <8C64B1D2-B326-44F3-8526-08B0AEEA29E4@gmail.com> References: <5196CEBE-CF2E-48AF-A496-3CE2FE1B6FD2@gmail.com> To: Hellmuth Vargas X-Mailer: Apple Mail (2.3445.8.2) List-Id: List-Help: List-Subscribe: List-Post: List-Owner: List-Archive: Precedence: bulk > On 19 Jun 2018, at 21:14, Hellmuth Vargas wrote: >=20 >=20 > Hi >=20 > with partial sum: >=20 > with recursive pizza (name, step, ingredient, quantity, unit, rel_qty, = path, weight) > as ( > select > name, step, ingredient, quantity, unit > , quantity::numeric(10,2) > , step::text > , case when unit =3D 'g' then quantity::numeric(10,2) = else null end > from recipe > where name =3D 'pizza' > union all > select > recipe.name, recipe.step, recipe.ingredient, = recipe.quantity, recipe.unit > , (pizza.rel_qty * recipe.quantity)::numeric(10,2) > , pizza.path || '.' || recipe.step > , case when recipe.unit =3D 'g' then (pizza.rel_qty * = recipe.quantity)::numeric(10,2) else null end > from pizza > join recipe on (recipe.name =3D pizza.ingredient) > ) > select path, ingredient, quantity, rel_qty, unit, weight,sum(weight) = over(partition by split_part(path,'.',1)) as parcial_weight, sum(weight) = over() as total_weight > from pizza > order by path; >=20 > path | ingredient | quantity | rel_qty | unit | weight | = parcial_weight | total_weight > = -------+--------------+----------+---------+-------+--------+-------------= ---+-------------- > 1 | tomato sauce | 1.00 | 1.00 | pcs | | = 113.00 | 313.00 > 1.1 | tomato | 100.00 | 100.00 | g | 100.00 | = 113.00 | 313.00 > 1.2 | basil | 10.00 | 10.00 | g | 10.00 | = 113.00 | 313.00 > 1.3 | salt | 3.00 | 3.00 | g | 3.00 | = 113.00 | 313.00 > 2 | pizza bottom | 1.00 | 1.00 | pcs | | = 200.00 | 313.00 > 2.2 | dough | 1.00 | 1.00 | pcs | | = 200.00 | 313.00 > 2.2.1 | flour | 150.00 | 150.00 | g | 150.00 | = 200.00 | 313.00 > 2.2.2 | water | 50.00 | 50.00 | g | 50.00 | = 200.00 | 313.00 > 2.2.3 | salt | 1.00 | 1.00 | pinch | | = 200.00 | 313.00 > (9 rows) That is certainly an interesting solution and it begs the question = whether a text field ('path') is actually the right representation of = the hierarchy (some type of array would seem to be a better fit). Good = out-of-the-box thinking! This is probably usable for my actual case, so thanks for that, wouldn't = have thought of it myself (even though I already had all the right = "bits" in place!). On the more theoretical front: The question remains whether it is = possible to calculate fields in post-order tree traversal. I think that = would be a semantically proper way to express this type of problem and = it wouldn't need the kinds of pre/post-processing that after-the-fact = aggregation (like in above solution) requires. So, leaner, and probably = faster. That implies that the SQL committee thought of the possibility in the = first place though, which I'm beginning to doubt... > El mar., 19 de jun. de 2018 a la(s) 11:49, Hellmuth Vargas = (hivs77@gmail.com) escribi=C3=B3: > Hi >=20 > with recursive pizza (name, step, ingredient, quantity, unit, rel_qty, = path, weight) > as ( > select > name, step, ingredient, quantity, unit > , quantity::numeric(10,2) > , step::text > , case when unit =3D 'g' then quantity::numeric(10,2) = else null end > from recipe > where name =3D 'pizza' > union all > select > recipe.name, recipe.step, recipe.ingredient, = recipe.quantity, recipe.unit > , (pizza.rel_qty * recipe.quantity)::numeric(10,2) > , pizza.path || '.' || recipe.step > , case when recipe.unit =3D 'g' then (pizza.rel_qty * = recipe.quantity)::numeric(10,2) else null end > from pizza > join recipe on (recipe.name =3D pizza.ingredient) > ) > select path, ingredient, quantity, rel_qty, unit, weight, sum(weight) = over() as total_weight > from pizza > order by path; >=20 > path | ingredient | quantity | rel_qty | unit | weight | = total_weight > = -------+--------------+----------+---------+-------+--------+-------------= - > 1 | tomato sauce | 1.00 | 1.00 | pcs | | = 313.00 > 1.1 | tomato | 100.00 | 100.00 | g | 100.00 | = 313.00 > 1.2 | basil | 10.00 | 10.00 | g | 10.00 | = 313.00 > 1.3 | salt | 3.00 | 3.00 | g | 3.00 | = 313.00 > 2 | pizza bottom | 1.00 | 1.00 | pcs | | = 313.00 > 2.2 | dough | 1.00 | 1.00 | pcs | | = 313.00 > 2.2.1 | flour | 150.00 | 150.00 | g | 150.00 | = 313.00 > 2.2.2 | water | 50.00 | 50.00 | g | 50.00 | = 313.00 > 2.2.3 | salt | 1.00 | 1.00 | pinch | | = 313.00 > (9 rows) >=20 >=20 >=20 >=20 >=20 > El mar., 19 de jun. de 2018 a la(s) 08:39, Alban Hertroys = (haramrae@gmail.com) escribi=C3=B3: > Hi all, >=20 > I'm struggling with a hierarchical query where I'm tasked to calculate = weights of items in an (exploded) Bill of Materials, based on the = weights of their components. Not all components are measured with a = weight, sometimes there are pieces, meters, areas, etc, and the = hierarchy is of varying levels of depth. >=20 > It would help if I could track a sum() throughout the explosion that = would write back onto parent rows when the recursion returns: postorder = traversal. >=20 > I created a simplified example about making pizza: >=20 > CREATE TABLE ingredient ( > name text NOT NULL > ); >=20 > CREATE TABLE recipe ( > name text NOT NULL, > ingredient text NOT NULL, > quantity numeric(6,2) NOT NULL, > unit text NOT NULL, > step integer NOT NULL > ); >=20 > COPY ingredient (name) FROM stdin; > tomato > basil > salt > tomato sauce > flour > water > yeast > dough > pizza bottom > pizza > \. >=20 > COPY recipe (name, ingredient, quantity, unit, step) FROM stdin; > tomato sauce tomato 100.00 g 1 > dough flour 150.00 g 1 > tomato sauce basil 10.00 g 2 > pizza pizza bottom 1.00 pcs 2 > tomato sauce salt 3.00 g 3 > dough salt 1.00 pinch 3 > pizza tomato sauce 1.00 pcs 1 > pizza bottom dough 1.00 pcs 2 > dough water 50.00 g 2 > \. >=20 > ALTER TABLE ONLY ingredient > ADD CONSTRAINT ingredient_pkey PRIMARY KEY (name); >=20 > ALTER TABLE ONLY recipe > ADD CONSTRAINT recipe_pkey PRIMARY KEY (name, ingredient); >=20 > ALTER TABLE ONLY recipe > ADD CONSTRAINT recipe_ingredient_fkey FOREIGN KEY (ingredient) = REFERENCES ingredient(name); >=20 > ALTER TABLE ONLY recipe > ADD CONSTRAINT recipe_name_fkey FOREIGN KEY (name) REFERENCES = ingredient(name); >=20 >=20 > A query listing the recipe for 'pizza' would be as follows: > development=3D> with recursive pizza (name, step, ingredient, = quantity, unit, rel_qty, path, weight) > as ( > select > name, step, ingredient, quantity, unit > , quantity::numeric(10,2) > , step::text > , case when unit =3D 'g' then quantity::numeric(10,2) = else null end > from recipe > where name =3D 'pizza' > union all > select > recipe.name, recipe.step, recipe.ingredient, = recipe.quantity, recipe.unit > , (pizza.rel_qty * recipe.quantity)::numeric(10,2) > , pizza.path || '.' || recipe.step > , case when recipe.unit =3D 'g' then (pizza.rel_qty * = recipe.quantity)::numeric(10,2) else null end > from pizza > join recipe on (recipe.name =3D pizza.ingredient) > ) > select path, ingredient, quantity, rel_qty, unit, weight > from pizza > order by path; >=20 > path | ingredient | quantity | rel_qty | unit | weight=20 > -------+--------------+----------+---------+-------+-------- > 1 | tomato sauce | 1.00 | 1.00 | pcs | =20 > 1.1 | tomato | 100.00 | 100.00 | g | 100.00 > 1.2 | basil | 10.00 | 10.00 | g | 10.00 > 1.3 | salt | 3.00 | 3.00 | g | 3.00 > 2 | pizza bottom | 1.00 | 1.00 | pcs | =20 > 2.2 | dough | 1.00 | 1.00 | pcs | =20 > 2.2.1 | flour | 150.00 | 150.00 | g | 150.00 > 2.2.2 | water | 50.00 | 50.00 | g | 50.00 > 2.2.3 | salt | 1.00 | 1.00 | pinch | =20 > (9 rows) >=20 >=20 > With these results, I somehow need to calculate that the weights of = 'tomato sauce', 'dough' and 'pizza bottom' are 113 g, 200 g and 200 g = respectively, bringing the total weight of 'pizza' to 313 g. >=20 > My first thought was to traverse the result of this recursive CTE = using another one, but in the opposite direction. But since this tends = to be kept as a temporary materialized result set with no indices, = that's not performing great and it adds a fair amount of complexity to = the query too. >=20 > Then I realised that if we somehow could track the sum() of 'weight' = throughout exploding these recipe items, by using a postorder tree = traversal, the desired result would be readily available to pick up when = the recursive CTE travels up through the hierarchy. >=20 > In above example; When the CTE would reach '1.3 salt', it would write = the summed 'weight' value 113 back on the result for '1 tomato sauce' = and when it reached '2.2.2 salt' it would write back 200 to '2.2 dough' = and then 200 to '2 pizza bottom'. >=20 > Is that possible? >=20 > I've seen a couple of "solutions" on the internet that just summed up = the results of the CTE, but that won't do as it would not put the = correct weights onto intermediate levels of the tree as far as I can see = (in above, the weight of 'dough'). >=20 >=20 > Regards, >=20 > Alban Hertroys >=20 >=20 > PS. Don't try to make pizza using this recipe, it probably won't = succeed. I forgot the yeast, for one thing, and quantities are probably = way off. Not to mention that there are probably more ingredients = missing=E2=80=A6 >=20 > PS2. In my real case the ingredients have a base quantity and unit, = which makes adjusting to relative quantities actually viable. Those = aren't necessary to describe the problem though. > -- > If you can't see the forest for the trees, > cut the trees and you'll find there is no forest. Regards, Alban Hertroys -- If you can't see the forest for the trees, cut the trees and you'll find there is no forest.