I need to calculate the average score of a list of userId.
I have a table user_place_score
:
(user_id, place_id, score)
Sometimes I do not have the score (no row for (user_id,place_id)
in the table) so I need to fetch a "default" score from the table default_place_score
:
(place_id, score)
Is is possible in PostgreSQL to do this in one query? For a given list of users and one place_id
, select all their scores in the user_place_score
and if no row is found then take the score found if the default_place_score
table?
Basically I want to avoid doing this kind of stuff:
for (Integer userId : userIds) {
score = (query to fetch the score for this userId)
if (score == null)
defaultScore = (query to fetch the default score for this PlaceId)
total = total + defaultScore
}
//return the average
return total/numberOfUser
NULL
in score column? Or not? (you say "not row found") If there is no row, how do you know a user's place_id? – ypercube Jan 13 at 21:51place_id
? – ypercube Jan 13 at 22:05