I am using Postgresql 13.0 and have a table category as follows:
cat_id | cat_name | piece | weight | is_tag_stock
--------------------------------------------
4 | cat1 | 20 | 10 | true
5 | cat2 | 30 | 15 | false
4 | cat1 | 40 | 5 | false
4 | cat1 | 50 | 30 | false
How do I group by in such a way that for one category, the query yields one record, and based on is_tag_stock, it should form JSON? Also, the JSON should contain the summation of the piece and weight field grouped by cat_id and cat_name. If is_tag_stock is true, then the piece and weight should be added to the tagged field else in the untagged field.
NOTE: For one cat_id, there would be only one cat_name. cat_name is included in the table just to avoid join.
Expected Output
cat_id | cat_name | tagged | untagged
------------------------------------------------------------------------------
4 | cat1 | {"piece":20,"weight":10} | {"piece":90,"weight":35}
5 | cat2 | {"piece":0,"weight":0} | {"piece":30,"weight":15}
{...}
structure is not a JSON array, it's a JSON object. An array would be a list of such objects enclosed in square brackets:[{...}, {...}, ...]
. – Andriy M Dec 29 '20 at 10:01