Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Looking for Postgres query which can provide output like MongoDB group by function

Product table

|_id|name  |
|---|------|
|3  |Laptop|

Size table

|_id|product_id|size|
|---|----------|----|
|5  |3         |15  |
|6  |3         |17  |

Query:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

select tp._id, tp.name, ts.size from test_product tp 
  left join test_size ts on tp._id = ts.product_id 
  group by tp._id, tp.name, ts.size
where tp._id = 3 limit 10 offset 0

Current output:

|_id|name  |size|
|---|------|----|
|3  |Laptop|15  |
|3  |Laptop|17  |

Expected output

|_id|name  |size   |
|---|------|-------|
|3  |Laptop|[15,17]|

Note:
Due to current query I’m getting 2 record for the same product and my limit and offset query logic is getting false and not getting proper count. I’m not well aware of Postgres queries for this kind of situation. So I need solution for this so my limit and offset logic will be correct for fetching data and for this query my count of product will be 1.

>Solution :

Use array_agg():

SELECT
    tp._id,
    tp.name,
    ARRAY_AGG(ts.size ORDER BY ts.size) -- ORDER BY to get consistent results
FROM
    test_product tp
    LEFT JOIN test_size ts ON tp._id = ts.product_id 
GROUP BY
    tp._id,
    tp.name 
WHERE
    tp._id = 3 
LIMIT 10 
OFFSET 0;

The ORDER BY within the aggregation is optional, but it’s always nice to get consistent results over and over again.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading