如何根据mysql总和找出一行的排名?

时间:2009-09-13 04:35:46

标签: php sql mysql

我想找到一行的排名/数量。我不确定我是否解释得这么好,所以我会试试。

我有查询

$sql = 'SELECT SUM(amount) AS total FROM sales ORDER BY total DESC';

$res = mysql_query($sql);

while($row = mysql_fetch_array($res)) {

// go through and print each row biggest 'total' first
echo $row['total'] . '<br />';

}

现在我想通过根据最大'总数'为数字'1'给每个人排名。

所以我可以通过做一些计算来实现这一点:

$sql = 'SELECT SUM(amount) AS total FROM sales ORDER BY total DESC';

$res = mysql_query($sql);

$rank = 1;

while($row = mysql_fetch_array($res)) {



// go through and print each row biggest 'total' first
echo 'rank: ' . $rank . ', ' . $row['total'] . '<br />';

$rank = $rank + 1;

}

这很好并且有效。但是我想要做的是,能够确定没有php的行的排名,所以我可以根据销售表中的联盟ID来进行sql查询。

因此,例如,我有100行销售数据,其中每个行都附有一个会员ID,我如何才能根据最大总会员数来获得排名?

2 个答案:

答案 0 :(得分:1)

您可以使用递归变量来执行此操作,如下所示:

select 
    @rownum:=@rownum+1 as rank,
    sum(amount) as total
from 
    sales,
    (select @rownum:=0) a
order by total desc

要获得某个联盟会员的排名,您必须这样做:

select
    a.*,
    t.rank,
    t.total
from
    affiliates a
    inner join (
        select 
            @rownum:=@rownum+1 as rank,
            affiliate_id,
            sum(amount) as total
        from 
            sales,
            (select @rownum:=0) r
        group by affiliate_id
        order by total desc) t on
       a.affiliate_id = t.affiliate_id
where
    a.affiliate_id = 342

现在(相对)慢,因为每次都必须进行表扫描。

如果你没有使用MySQL,我会建议一个子查询,但总的来说,MySQL可能会极其优化子查询。看起来它对我来说相当缓慢,但我没有对它进行基准测试。无论如何,你可以这样做:

select
    a.*,
    (select
        count(*)+1
    from
        (select affiliate_id from sales 
         group by affiliate_id having sum(amount) >
            (select sum(amount) from sales where affiliate_id = a.affiliate_id)))
        as rank
from
    affiliates a
where
    a.affiliate_id = 342

答案 1 :(得分:-1)

DB的其他实现具有row_number和row_number_count。如果您使用的是MySQL,我建议您查看此walk-around