2

在我的事件表中,我有一个名为 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 />";

}
4

2 回答 2

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';

SQLFIDDLE 演示在这里

编辑: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 />";
于 2012-08-22T09:48:34.720 回答
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++;
}
于 2012-08-22T09:52:32.953 回答