I'm writing a query that lists all the challenges (+ score) a user has taken today, or in case he hasn't taken any challenge on this day that outputs the last challenge he has ever taken.
I've written the following query, that seems to give me what I want, but it seems like a very convoluted way of achieving this. I was wondering if there isn't a better way of achieving the same result.
SELECT COALESCE (c.id, coal) challenge_id, max(e.accuracy_score) score
FROM (select id, creation_date from challenge WHERE learner_id = $1 AND creation_date > CURRENT_DATE) c
FULL OUTER JOIN
COALESCE (
(SELECT id FROM challenge WHERE learner_id = $1 AND creation_date > CURRENT_DATE LIMIT 1),
(SELECT id FROM challenge WHERE learner_id = $1 ORDER BY creation_date DESC LIMIT 1)
) AS coal
ON coal = c.id
LEFT JOIN experience e ON COALESCE (c.id, coal)=e.challenge_id
GROUP BY COALESCE (c.id, coal) ORDER BY COALESCE (c.id, coal) ASC