Order items are stored together with category path which comes from a tree structure. That is, Category 2 is a child to Category 1 and Category 3 is a child of 2 etc.
This is a PostgreSQL database.
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 |
What I would like to get is column with the quantity including subcategories.
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 |
I found this post that is similar but had no luck. Recursive sum in tree structure
I've tried solving this with a CTE but can't seem to get it right. Any suggestions are welcome :)