I have a table. ShopUnit: name, price, type (OFFER,CATEGORY), parentID - (fk to shopUnit (self)).
I have an id. I need to return row with this id. and every children. If item or children have a type == CATEGORY. I need to set price = AVG value for children of a row.
I think of a recursive
with recursive unit_tree as (
select s1.id,
s1.price,
s1.parent_id,
s1.type,
0 as level
from shop_unit s1
where s1.id = 'a'
union all
select s2.id,
s2.price,
s2.parent_id,
s2.type,
level + 1
from shop_unit s2
join unit_tree ut on ut.id = s2.parent_id
)
select unit_tree.id,
unit_tree.parent_id,
unit_tree.type,
unit_tree.level,
unit_tree.price
from unit_tree;
but how do i count the average for every category.
here's example
{
"id": "3fa85f64-5717-4562-b3fc-2c963f66a111",
"name": "Категория",
"type": "CATEGORY",
"parentId": null,
"date": "2022-05-28T21:12:01.516Z",
"price": 6,
"children": [
{
"name": "Оффер 1",
"id": "3fa85f64-5717-4562-b3fc-2c963f66a222",
"price": 4,
"date": "2022-05-28T21:12:01.516Z",
"type": "OFFER",
"parentId": "3fa85f64-5717-4562-b3fc-2c963f66a111"
},
{
"name": "Подкатегория",
"type": "CATEGORY",
"id": "3fa85f64-5717-4562-b3fc-2c963f66a333",
"date": "2022-05-26T21:12:01.516Z",
"parentId": "3fa85f64-5717-4562-b3fc-2c963f66a111",
"price": 8,
"children": [
{
"name": "Оффер 2",
"id": "3fa85f64-5717-4562-b3fc-2c963f66a444",
"parentId": "3fa85f64-5717-4562-b3fc-2c963f66a333",
"date": "2022-05-26T21:12:01.516Z",
"price": 8,
"type": "OFFER"
}
]
}
]
}