1

我的问题可能很容易回答(抱歉),但我找不到解决方案。

我有一张这样的桌子:

id / date  
1 / 2013-5-5 13:44:12  
1 / 2013-5-5 15:34:19  
1 / 2013-6-5 05:14:07  
2 / 2012-3-4 06:33:33  
2 / 2013-5-5 12:23:10  
3 / 2012-5-7 11:43:17   

我想要的是这个:

id / date / position  
1 / 2013-5-5 13:44:12 / 1    
1 / 2013-5-5 15:34:19 / 2  
1 / 2013-6-5 05:14:07 / 3   
2 / 2012-3-4 06:33:33 / 1   
2 / 2013-5-5 12:23:10 / 2   
3 / 2012-5-7 11:43:17 / 1  

所以每个 id 的最早日期应该是位置 1,第二个最早的日期是 2,依此类推。如何在 MySQL 中创建位置列?

非常感谢!

4

3 回答 3

3

Unfortunately, MySQL doesn't have windowing functions to assign a row number to the data. But there are a few ways that you can get the result, you could return this position number using a subquery similar to the following:

select t.id,
  t.date,
  (select count(*)
   from yourtable r
   where r.id = t.id
     and r.date <= t.date) position
from yourtable t
order by t.id, t.date;

See SQL Fiddle with Demo.

You could also implement user defined variables:

select id, date, position
from
(
  select t.id,
    t.date,
    @row:=case 
            when @prev=t.id and @pd<= t.date
            then @row else 0 end +1 position,
    @prev:=t.id,
    @pd:=t.date
  from yourtable t
  cross join (select @row:=0, @prev:=0, @pd:=null) c
  order by t.id, t.date
)d

See SQL Fiddle with Demo

于 2013-08-07T12:04:55.077 回答
1

You could use session variables, but I'm sentimental; I like the slower, old-fashioned method...

 SELECT x.*
      , COUNT(*) rank 
   FROM my_table x 
   JOIN my_table y 
     ON y.id = x.id 
    AND y.date <= x.date 
  GROUP 
     BY id,date;
于 2013-08-07T12:07:24.210 回答
0

计算每个日期下方的行数:

UPDATE
    `table`
SET
    position = 
    (
        SELECT
            COUNT(1) + 1
        FROM
            `table` t
        WHERE
            t.`date` < `table`.`date`
            AND t.id = table.id
        ORDER BY
            `date`
    )

SQL Fiddle(仅选择可用,但它是一样的)

于 2013-08-07T12:06:06.800 回答