I have a table in the following format:
I feel like this should be simple but I'm struggling to come up with a performant query that can perform aggregations based on other rows with a shared key. For example, I want to sum the rows for a user with the key MediaLength
but only if the rows with the key Score
that share the event_id
are greater than or equal to 3.
The result from a simple sum:
SELECT SUM(value::float) FROM data WHERE key = 'MediaLength' AND user_id = '9765f312-0d0b-4db0-b4c5-217eec81d7c3'
Result: 40
The result I am trying to achieve here is 15
. In the table above you can see the rows are children of an event. I only want to sum the value
column where key = 'MediaLength'
and its sister row with key = 'Score'
has value >= 3
.
This is the query I have tried so far but it seems a bit messy and also doesn't work due to a more than one row returned by subquery
error:
select
sum(value::float)
filter (where (
select d.value::float
from data d
where d.event_id = event_id
and d.key = 'Score'
) >= 3)
from data
where user_id = '9765f312-0d0b-4db0-b4c5-217eec81d7c3'
This is a simple example but in the future I would need to filter on potentially multiple other keys as well, so any advice on how to extend that is also hugely appreciated.