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

How can I do order by without using it in group by

I have a table called products and I would like to get all my products with same asin inside one row and concat their skus in one column I came up with something like this but I have problem with order by sku and other columns that are not inside group by. Is there any solution?

my sql:

SELECT prod.asin, string_agg(p.sku,', ') AS skus,
  SUM(p.amazon_inv_available) AS amazon_available_inv,
  SUM(p.amazon_inv_total) AS amazon_total_inv
FROM (
  SELECT id, asin, sku, amazon_inv_available, amazon_inv_total
  FROM products 
  WHERE store_id IN (12, 10, 11)
  ORDER BY sku
) AS prod
LEFT JOIN products AS p  ON prod.asin = p.asin
GROUP by prod.asin

dbfiddle

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

Desired result when order by prod.sku

enter image description here

order by prod.sku DESC

enter image description here

>Solution :

You can add ORDER BY to STRING_AGG() to specify the ordering of the concatenated values.

For example:

SELECT
  asin, 
  string_agg(sku,', ' order by id) AS skus,
  SUM(amazon_inv_available) AS amazon_available_inv,
  SUM(amazon_inv_total) AS amazon_total_inv
FROM products
WHERE store_id IN (12, 10, 11)
GROUP by asin
ORDER BY amazon_available_inv

Result:

 asin  skus        amazon_available_inv  amazon_total_inv 
 ----- ----------- --------------------- ---------------- 
 B     HH, QW      200                   400              
 A     AC, TT, DD  300                   600              

See db<>fiddle.

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