树结构为字符串的树结构中的递归和

时间:2020-11-06 09:47:11

标签: sql postgresql sum hierarchical-data recursive-query

订单项与来自树结构的类别路径一起存储。 也就是说,类别2是类别1的子级,类别3是2等的子级。

这是一个PostgreSQL数据库。

create table order_item (
    id bigserial not null,
    quantity int not null,
    category_path text
);

insert into order_item (quantity, category_path) VALUES 
(5, 'Category 1'),
(7, 'Category 1||Category 2'),
(3, 'Category 1||Category 2||Category3'),
(9, 'Category 1||Category 2||Category3'),
(2, 'Category 4'),
(11, null),
(4, null);
select category_path, sum(quantity) from order_item group by category_path order by category_path;

category_path                          | quantity |
---------------------------------------------------
Category 1                             |        5 |
Category 1||Category 2                 |        7 |
Category 1||Category 2||Category3"     |       12 |
Category 4                             |        2 |
<null>                                 |       15 |

我想得到的是带有数量的列,包括子类别。

category_path                          | quantity | quantityIncludingSubCategories |
-----------------------------------------------------------------------------------
Category 1                             |        5 |                            24  |
Category 1||Category 2                 |        7 |                            19  |
Category 1||Category 2||Category3"     |       12 |                            12  |
Category 4                             |        2 |                             2  |
<null>                                 |       11 |                            11  |

我发现这篇帖子很相似,但是没有运气。 Recursive sum in tree structure

我曾尝试通过CTE解决此问题,但似乎无法正确解决。 欢迎任何建议:)

1 个答案:

答案 0 :(得分:0)

您已经有了每个节点的路径,因此不需要递归。简单的方法是使用相关子查询-或横向联接-路径上的模式匹配:

select oi.*, x.quantity1
from order_item oi
cross join lateral (
    select sum(oi1.quantity) quantity1
    from order_item oi1
    where oi1.category_path like oi.category_path || '%'
) x

Demo on DB Fiddle