Skip to content
Advertisement

How to aggregate json fields when using GROUP BY clause in postgres?

I have the following table structure in my Postgres DB (v12.0)

I am using GROUP BY query for this records, like below

Using which I will get the total pieces as 30. But how could I get the count of total pieces from material_detail group by material_id.

I want result something like this

As I am from MySQL background, I don’t know how to achieve this with JSON fields in Postgres.

Note: material_detail column is of JSONB type.

Advertisement

Answer

You are aggregating on two different levels. I can’t think of a solution that wouldn’t need two separate aggregation steps. Additionally to aggregate the material information all arrays of the item_id have to be unnested first, before the actual pieces value can be aggregated for each material_id. Then this has to be aggregated back into a JSON array.

Online example

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement