我感兴趣地阅读了以下有关在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
我一直在努力解决这个问题几个小时,没有任何令人满意的表现。任何帮助,将不胜感激!
答案 0 :(得分: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
答案 1 :(得分: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;