我继承了以下查询,它获取指定“尝试”(触地得分的橄榄球术语)的平均评分。希望我们仍然可以使用它。
SELECT i.id, i.title,
(
CASE
WHEN
COUNT( r.rating ) > 0
THEN
(
SUM( r.rating ) / COUNT( r.rating )
)
ELSE
0
END
) AS rating,
COALESCE( er.id, 0 ) AS has_existing_rating
FROM
(
SELECT 1 AS id, 'Try 1 – Israel Dagg v Chiefs.' as title UNION ALL
SELECT 2 AS id, 'Try 2 – Israel Dagg v Chiefs.' as title UNION ALL
SELECT 3 AS id, 'Try 3 – Leilia Masaga v Crusaders.' as title UNION ALL
SELECT 4 AS id, 'Try 4 – Israel Dagg v Chiefs.' as title UNION ALL
SELECT 5 AS id, 'Try 5 – Fred Flintstone v Hurricanes.' as title UNION ALL
SELECT 6 AS id, 'Try 6 – Israel Dagg v Chiefs.' as title UNION ALL
SELECT 7 AS id, 'Try 7 – Israel Dagg v Chiefs.' as title
) AS i
LEFT OUTER JOIN
tryPoll r
ON
i.id = r.try_id
<!--
Join this to the rating table AGAIN to see if the current
user has already rated the given try.
-->
LEFT OUTER JOIN
tryPoll er
ON
(
er.try_id = i.id
AND
er.ip_address = '#cgi.remote_addr#'
AND
er.user_agent = '#cgi.http_user_agent#'
)
GROUP BY
i.id,
r.try_id,
er.id,
i.title
ORDER BY
i.id ASC
因此,给定下表(在这种情况下,评级 = 1 仅表示一票)......
尝试投票
id try_id rating ip_address user_agent
------------------------------------------------------
1 2 1 58.28.220.51 Mozilla/5.0 blah
2 2 1 58.28.220.52 Mozilla/5.0 blah
3 6 1 58.28.220.53 Mozilla/5.0 blah
4 4 1 58.28.220.54 Mozilla/5.0 blah
...查询将返回 try_id #2 的平均评分 (1 + 1) / 2 = 1
但是,我需要调整此查询以返回特定 TRY 的评分相对于所有尝试的评分的百分比。即,在上面的示例中,确定所有尝试的所有评分中有多少百分比归因于 try_id #2
我将如何做到这一点?