在我的事件表中,我有一个名为Pos1的列,其中包含从A到E的ID。我需要计算“E”在列中出现的次数以及它与其他数字并排的位置。
例如,在此表中,“E”出现 1 时间,排名 4 (D = 3,A = 2,C = 2,E = 1,B = 0)。
Pos1
E
C
D
C
D
D
A
A
我是一个完整的SQL业余爱好者,所以我最接近的是打印每个ID计数的数组,但我需要将其限制为计算单个ID 和打印排名
$query = "SELECT Pos1, COUNT(Pos1) FROM Events GROUP BY Pos1";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['COUNT(Pos1)'] ."<br />";
}
答案 0 :(得分:5)
试试这个:
SELECT Pos1, a.cnt, rank
FROM(
SELECT a.Pos1, a.cnt, (@rank := @rank + 1) AS rank
FROM(
SELECT Pos1, COUNT(Pos1) cnt
FROM Events
GROUP BY Pos1
) a, (SELECT @rank := 0) b
ORDER BY a.cnt DESC
)a
WHERE a.pos1 = 'E';
编辑:php代码
$query = "SELECT Pos1, a.cnt, rank
FROM(
SELECT a.Pos1, a.cnt, (@rank := @rank + 1) AS rank
FROM(
SELECT Pos1, COUNT(Pos1) cnt
FROM Events
GROUP BY Pos1
) a, (SELECT @rank := 0) b
ORDER BY a.cnt DESC
)a
WHERE a.pos1 = '$pos1'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_row($result);
echo $row['Pos1']." ".$row['cnt']." ".$row['rank']."<br />";
答案 1 :(得分:0)
或者在PHP中排名:
$query = "SELECT Pos1, COUNT(Pos1) AS qty FROM Events GROUP BY Pos1 ORDER BY qty DESC";
$result = mysql_query($query) or die(mysql_error());
$rank=1;
while($row = mysql_fetch_array($result))
{
echo $rank.": ".$row['Pos1']."(".$row['qty'].")<br />";
$rank++;
}