我正在使用PHP / MySQL创建一个显示比赛结果的网站。我想显示10个最难的比赛的统计数据,即大多数人DNF的比赛。我是这样做的:
select raceid,race.name,race.location,race.date,count(result.raceid) as dnfs
from result
inner join race on result.raceid=race.id
where result.place=0
group by result.raceid
order by dnfs desc limit 10
但这并没有考虑到比赛中的人数。如何修改查询以返回percentDNF(dnfs / totalracers)并按该列排序?地点= 0表示DNF。
答案 0 :(得分:12)
删除WHERE
子句并使用CASE
语句来计算did-not-finish值。然后由总赛手划分。像这样:
SELECT result.raceid, race.name, race.location, race.date,
COUNT(result.raceid) AS TOTAL,
SUM(CASE WHEN result.place = 0 THEN 1 ELSE 0 END) AS DNF,
SUM(CASE WHEN result.place = 0 THEN 1 ELSE 0 END) /
COUNT(result.raceid) AS PCT_DNF
FROM result
JOIN race ON result.raceid=race.id
GROUP BY result.raceid, race.name, race.location, race.date
ORDER BY SUM(CASE WHEN result.place = 0 THEN 1 ELSE 0 END) /
COUNT(result.raceid) DESC LIMIT 10
答案 1 :(得分:3)
我不知道它是否运行mysql,在sql server中它可以是: select((从tbl中选择count(*)where critieie)* 100)/(从tbl中选择count(*))