我正在尝试计算一个团队在有序 MySQL 结果集中的排名,而我遇到的问题是检测第一个团队的平局以显示平局值。
例如,假设结果集如下:
team_id pts
---------------
1 89
2 87
3 76
4 76
5 52
我用以下 PHP 计算团队的排名:
$i = 0;
while($row = mysql_fetch_assoc($r)) { //iterate thru ordered (desc) SQL results
++$i;
($row['pts'] == $prev_val)
? $rnk = 'T-' . $rnk //same as previous score, indicate tie
: $rnk = $i; //not same as previous score
$rnk = str_replace('T-T-','T-',$rnk); //eliminate duplicative tie indicator
if ($row['team_id'] == $team_id) { //current team in resultset matches team in question, set team's rank
$arr_ranks['tp']['cat'] = 'Total Points';
$arr_ranks['tp']['actual'] = number_format($row['pts'],1);
$arr_ranks['tp']['league_rank'] = $rnk;
$arr_ranks['tp']['div_rank'] = $div_rnk;
}
else if ($i == 1) { //current team is category leader (rank=1) and is not team in question, set current team as leader
$arr_ranks['tp']['leader'] = "<a href='index.php?view=franchise&team_id=" . $row['team_id'] . "'>" . get_team_name($row['team_id']) . '</a> (' . number_format($row['pts'],1) . ')';
}
$prev_val = $row['pts']; //set current score as previous score for next iteration of loop
}
上面的“平局”逻辑将把#4队与#3队平局,但反之则不然。
换句话说,对于#3 队,$rnk = 3
,而对于#4 队,$rnk = T-3
。(两者都应该是“T-3”。)
所以问题就变成了:我如何在遍历结果时“向前看”以找出当前分数是否与列表后面的分数相同/重复,这样我就可以将它与随后的欺骗一起视为并列?
谢谢。
编辑:如果我首先将结果存储在表中,我可以实现 Ignacio 的代码,"wins"
如下所示:
select
s1.team_id,
t.division_id,
sum(s1.score>s2.score) tot_wins,
( select count(*)
from wins
where team_id <> s1.team_id
and wins > (select wins
from wins
where team_id = s1.team_id)
)+1 as rnk
from
scoreboard s1
left join teams t
on s1.team_id = t.team_id
left join scoreboard s2
on s1.year=s2.year and s1.week=s2.week and s1.playoffs=s2.playoffs and s1.game_id=s2.game_id and s1.location<>s2.location
group by s1.team_id
order by tot_wins desc;
这给出了以下结果:
team_id division_id tot_wins rnk
--------------------------------------
10 1 44 1
2 1 42 2
3 2 42 2
8 1 39 4
5 2 37 5
. . .
但是,我突然想到我已经得到了这个结果集,这实际上并没有解决我的问题。
为避免混淆,我已经单独发布了“跟进”问题。