排名sql列

时间:2014-01-17 09:11:04

标签: mysql sql

我有这样的表:

+--------+--------+--------+
| color  | fruit  | amount |
+--------+--------+--------+
| red    | cherry |    124 |
| red    | plum   |     23 |
| green  | gauva  |    119 |
| green  | pear   |     14 |
| orange | orange |     23 |
+--------+--------+--------+

我希望它添加这样的排名。

 +------+--------+--------+--------+
 | rank | color  | fruit  | amount |
 +------+--------+--------+--------+
 |    1 | red    | cherry |    124 |
 |    2 | red    | plum   |     23 |
 |    1 | green  | gauva  |    119 |
 |    2 | green  | pear   |     14 |
 |    1 | orange | orange |     23 |
 +------+--------+--------+--------+

我需要根据每种颜色的数量(单独)对其进行排名。 这可能吗?

4 个答案:

答案 0 :(得分:2)

select
color, fruit, amount,
case when (if(@prev_color != color, @rank:=1, @rank:=@rank + 1)) is null then null
     when (@prev_color := color) is null then null
else @rank end as rank
from your_table
, (select @rank:=0, @prev_color := null) v
order by color, amount desc

答案 1 :(得分:1)

如果根据amount可用性color的高amount给出排名,那么您还可以找到小于或大于rank值的行数。该行数将是相关color的{​​{1}}。

select
 ( select count( color ) from fruits_table 
   where color = f.color and amount >= f.amount
 ) as 'rank',
 color, fruit, amount 
from fruits_table f
order by color, amount desc
-- order by field( color, 'red', 'green', 'orange' ), amount desc
;

您可以使用color函数更改field的字段顺序,以根据需要显示在顶部或底部。请参阅上面注释的order by子句。

答案 2 :(得分:0)

试试这个

SELECT  @row_num := IF(@prev_value=o.Customer,@row_num+1,1) AS RowNumber
       ,colour
       ,fruit
       ,amount
       ,@prev_value := colour
  FROM Table1,
      (SELECT @row_num := 1) x,
      (SELECT @prev_value := '') y
  ORDER BY colour,amount DESC

答案 3 :(得分:0)

尝试使用行号函数,您可以在其中指定从何处开始编号(分区依据)以及如何组织该分区中的行(按顺序排序)。

 | rank | color  | fruit  | amount |
 +------+--------+--------+--------+
 |    1 | red    | cherry |    124 |
 |    2 | red    | plum   |     23 |
 |    1 | green  | gauva  |    119 |
 |    2 | green  | pear   |     14 |
 |    1 | orange | orange |     23 |
 +------+--------+--------+--------+
select distinct 
  row_number() over (partition by color order by amount desc) rank,
  color,
  fruit,
  amount
from
  foo
order by
  color, amount desc

您会发现行编号从每种新颜色开始,而在每种颜色中,行将按降序排序。