通过对特定陪审团的平均投票对团队进行排序

时间:2016-02-17 14:02:58

标签: sql postgresql

我有以下架构:

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

这适用于以下情况:

  • 团队投票选出的评委会
  • 团队投票选出的陪审团和其他陪审团(其他陪审团的投票未被考虑)
  • 团队根本没有投票(团队出现在列表末尾)

它不适用于以下情况:

  • 该团队被选为另一个评审委员会但未被选中的评审团(在这种情况下,团队没有出现在名单中)

我怎样才能做到这一点。

1 个答案:

答案 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