0

我感兴趣地阅读了以下关于在 MySQL 中模拟 rownum 的博客文章:

http://craftycodeblog.com/2010/09/13/rownum-simulation-with-mysql/

我想扩展这个概念,让行号在满足特定条件时重置,即其他一些列更改值,因此结果将如下所示:

  id | date       | rownum
-----+------------+--------
   1 | 2013-03-20 |      1
   2 | 2013-03-20 |      2
   3 | 2013-03-20 |      3
   4 | 2013-03-21 |      1   <-- rownum resets because date changes
   5 | 2013-03-21 |      2
   6 | 2013-03-21 |      3
   7 | 2013-03-22 |      1
   8 | 2013-03-22 |      2

几个小时以来,我一直试图弄清楚这一点,但没有任何令人满意的表现。任何帮助,将不胜感激!

4

2 回答 2

1

您可以使用以下方法实现用户定义的变量以获取每组日期的行号:

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

请参阅带有演示的 SQL Fiddle

于 2013-03-29T19:23:20.920 回答
0

这有效,请参阅http://www.sqlfiddle.com/#!2/e7f5e/11

SELECT if(changed, @rownum:=1, @rownum:=@rownum + 1) as rownum, rowdate
FROM (SELECT if(@lastdate=rowdate, '', @lastdate:=rowdate) as changed, rowdate
      FROM dates) flagged,
     (SELECT @rownum:= 0, @lastdate:='') setup;
于 2013-03-29T19:53:25.693 回答