我有以下架构:
teams(id, name)
jury(id, name)
criteria(id, name, coefficient, jury_id)
vote(id, team_id, jury_id, value, criterion_id)
我想得到每个团队并通过对特定评审团的平均投票来订购。
这是我当前的SQL:
SELECT teams.*,
SUM(votes.value * criteria.coefficient) / SUM(criteria.coefficient) AS rating
FROM "teams"
LEFT JOIN "votes" ON "teams"."id" = "votes"."team_id"
LEFT JOIN "criteria" ON "votes"."criterion_id" = "criteria"."id"
WHERE (votes.jury_id = 3510 OR votes.jury_id IS NULL)
GROUP BY teams.id
ORDER BY rating DESC NULLS LAST, teams.id
这适用于以下情况:
它不适用于以下情况:
我怎样才能做到这一点。
答案 0 :(得分:0)
我终于带来了以下SQL:
SELECT "teams".*
FROM (
SELECT teams.*, SUM(votes.value * criteria.coefficient) / SUM(criteria.coefficient) AS rating, teams.id
FROM "teams"
LEFT JOIN "votes" ON "teams"."id" = "votes"."team_id"
LEFT JOIN "criteria" ON "votes"."criterion_id" = "criteria"."id"
WHERE (votes.jury_id = 3613 OR votes.jury_id IS NULL)
GROUP BY teams.id
UNION
SELECT teams.*, NULL AS rating, teams.id
FROM "teams"
INNER JOIN "votes" ON "votes"."team_id" = "teams"."id"
INNER JOIN "criteria" ON "criteria"."id" = "votes"."criterion_id"
GROUP BY teams.id HAVING EVERY(votes.jury_id != 3613)
) AS teams
ORDER BY rating DESC NULLS LAST, teams.created_at
但是,我无法对teams.id进行排序,因为它表示列不明确。我尝试用另一个别名替换“AS团队”但没有成功,所以我使用了另一个列created_at
。