0

I want to group by the foolowing table but I also need to group the column ID as depitected on the image.

enter image description here

SELECT SUM(ml),sku,name FROM consumos 
GROUP BY sku,name
ORDER BY name

enter image description here

Any ideas?

Best regards

2
  • Tag your question with the database you are using. Commented Nov 14, 2020 at 13:05
  • Please do not post code as images. See here for more details why: meta.stackoverflow.com/questions/285551 Commented Nov 14, 2020 at 13:08

2 Answers 2

1

Looks like you want a JSON array. This can be done using jsonb_agg():

select name, sku, ml, jsonb_agg(id)
from the_table
group by name, sku, ml;
Sign up to request clarification or add additional context in comments.

Comments

0

In standard SQL, this would look like:

select name, sku, ml,
       '[' || listagg(id, ',') within group (order by id) || ']' as ids
from t
group by name, sku, ml
order by name, count(*);

However, not all databases support that standard operator || for string concatenation. And not all databases call their string aggregation operator listagg(). So you might need to tweak the query for your database.

EDIT:

In Postgres, this would be:

select name, sku, ml,
       '[' || string_agg(id, ',' order by id)  || ']' as ids
from t
group by name, sku, ml
order by name, count(*);

1 Comment

Hi, i am using postgresql. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.