4

Given the following input data:

id category
1 A
1 B
2 A
2 R
2 C
3 Z

I aim aiming to get the following output table:

id categories
1 {"A","B"}
2 {"A","R","C"}
3 {"Z"}

using the following query:

SELECT DISTINCT id,
                ARRAY(SELECT DISTINCT category::VARCHAR FROM test) AS categories
FROM my_table

But what I get is the following table:

id categories
1 {"A","B","R","C","Z"}
2 {"A","B","R","C","Z"}
3 {"A","B","R","C","Z"}

How can I obtain the desired output?

Note: The GROUP BY clause did not work in this case as I'm not using an aggregation function.

2 Answers 2

4

What about using the JSON_AGG aggregation function?

SELECT id,
       JSON_AGG(category) AS category
FROM tab
GROUP BY id
ORDER BY id

Check the demo here.

Sign up to request clarification or add additional context in comments.

2 Comments

I would like to keep it as an array as I then need to compare the content between two arrays...
then you can use ARRAY_AGG, which returns an array, does it work for you?
1

Assuming table has name test

select distinct id,
     array(select distinct category::varchar from test b where b.id = a.id) as categories
from test a

Comments

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.