Skip to content
Advertisement

How to filter and sum the array of integers in PostgreSQL

I have a task that requires to sum ALL topup_val performed by the id_user that had at least one topup_val ever by the amount of €15 exactly. This task needs to be solved in a single SELECT statement, without any window functions or subqueries (nested SELECT). I’m still a beginner in SQL so I found it struggle to finish this task.

I converted the topup_val rows for each id_user to array using array_agg(). However, I cannot filter the array using WHERE clause because WHERE clause is performed before the aggregate function.

Thank you so much!

Table topups

Converted to array

Expected result

My PostgreSQL queries

Advertisement

Answer

Between group by and order by you can further filter your result set with HAVING:

Demo: db<>fiddle

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement