在MySQL中获取组的位置

时间:2013-11-13 00:20:23

标签: mysql sql

我在此链接SQLFiddle上创建了表格,您可以在那里看到。有点名称和执行日期。我想每天补充这些人当天的表现。它应该从每天1开始(你可以在'Rank'中看到它)。结果应如下“结果”中所示:

Result
      ID |    date     | Rank | Name
      ---------------------------------
      1  | 2013-10-01  | 1    | Tom
      2  | 2013-10-01  | 2    | Karen
      3  | 2013-10-01  | 3    | Lucy
      4  | 2013-10-02  | 1    | Karen
      5  | 2013-10-02  | 2    | Tom
      6  | 2013-10-02  | 3    | Lucy
      7  | 2013-10-03  | 1    | Tom
      8  | 2013-10-03  | 2    | Lucy
      9  | 2013-10-03  | 3    | Karen
      10 | 2013-10-04  | 1    | Tom
      11 | 2013-10-04  | 2    | Lucy
      12 | 2013-10-04  | 3    | Karen

1 个答案:

答案 0 :(得分:3)

MySQL没有row_number()函数,但您可以使用变量伪造它。

select
    t.id,
    t.datum,
    t.rank,
    t.name
from ( 
    select
        s.id,
        s.datum,
        s.name,
        s.points,
        If(@datum <> s.datum, @rank := 1, @rank := @rank + 1) as rank, 
        @datum := s.datum
    from
        score_table s
            cross join (
            select
                @rank := null,
                @datum := '1980-01-01'
        ) as r 
    order by
        s.datum,
        s.points desc
    ) as t
order by 
    t.id,
    t.rank;

<强> Example SQLFiddle