0

Suppose I have a table Products that looks like:

category | items
-----------------
fruit    | {"apple", "banana"}
vegetable| {"carrot"}

and a table Prices that looks like:

name   | price
----------------
apple  | 1
banana | 2
carrot | 3

What's the simplest way to get an output like:

category | prices
-----------------
fruit    | {1, 2}
vegetable| {3}

Feel free to use CTE or any other niceties that will make the query easy to read.

1 Answer 1

1

Use unnest() to get elements of the items array which can be joined with names of the prices table. Finally, prices should be aggregate in groups by category:

select category, array_agg(price) as prices
from products
cross join unnest(items) u(item)
join prices on name = item
group by category
order by category;

 category  | prices 
-----------+--------
 fruit     | {1,2}
 vegetable | {3}
(2 rows)    
Sign up to request clarification or add additional context in comments.

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.