2013-08-07 49 views
1

我的问题可能很简单回答(对不起),但我找不到解决方案。每个编号的MySQL编号日期

我有这样的一个表:

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中创建位置列?

非常感谢!

回答

3

不幸的是,MySQL没有窗口函数来为数据分配一个行号。但也有,你可以得到结果的几个方法,你可以使用子查询类似这个位置号码返回到以下几点:

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; 

SQL Fiddle with Demo

你也可以实现用户定义的变量:

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 

SQL Fiddle with Demo

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(只选择可用的,但它的相同)

+0

位置需要有ID contraint,otherwhise你指望“全部”日期,但TC需要一定的ID组中的位置。 – dognose

+0

和他的表中的位置列在哪里? –

+0

@PraveenPrasannan我假设他想要在他的桌子上。 '我如何在MySQL中创建位置列,而不仅仅是选择它。 –

1

您可以使用sessi关于变量,但我很感性;我喜欢慢,老式的方法...

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; 
+0

不错,这也很好。 – hims056