SELECT
id = (
SELECT
TOP 1 id
FROM
learnings
WHERE
person_id = l.person_id
AND course_id = l.course_id
ORDER BY
(
CASE
WHEN state_id = 4 THEN 5
WHEN state_id = 2 THEN 4
WHEN state_id = 5 THEN 3
WHEN state_id = 3 THEN 2
ELSE state_id
END
) DESC,
score DESC,
creation_date DESC
),
l.person_id,
l.course_id
FROM
@LEARNINGS as l