select (@i:= @i+1) as rownum,t.* from t_visit t,(select @i:=0) as a;
先声明赋值,再使用
select @i:=0;
这里就是先声明@i这个变量,并且初始化值为0
@i:=@i+1
这里就是使用这个值,变量@i进行自增,等同于 i+=1
store | visit_date |
---|---|
家乐福古北店 | 2010-02-16 |
家乐福古北店 | 2010-01-30 |
家乐福古北店 | 2010-01-17 |
家乐福古北店 | 2010-01-07 |
家乐福巨峰店 | 2010-02-08 |
家乐福巨峰店 | 2010-02-06 |
莲花高中店 | 2010-03-01 |
store | visit_date | pre_visit_date | sequence |
---|---|---|---|
家乐福古北店 | 2010-02-16 | 2010-01-30 | 4 |
家乐福古北店 | 2010-01-30 | 2010-01-17 | 3 |
家乐福古北店 | 2010-01-17 | 2010-01-07 | 2 |
家乐福古北店 | 2010-01-07 | null | 1 |
家乐福巨峰店 | 2010-02-08 | 2010-02-06 | 2 |
家乐福巨峰店 | 2010-02-06 | null | 1 |
莲花高中店 | 2010-03-01 | null | 1 |
create table t_visit ( store varchar(20) null, visit_date varchar(20) null );
INSERT INTO t_visit (store, visit_date) VALUES ('家乐福古北店', '2010-02-16'); INSERT INTO t_visit (store, visit_date) VALUES ('家乐福古北店', '2010-01-30'); INSERT INTO t_visit (store, visit_date) VALUES ('家乐福古北店', '2010-01-17'); INSERT INTO t_visit (store, visit_date) VALUES ('家乐福古北店', '2010-01-07'); INSERT INTO t_visit (store, visit_date) VALUES ('家乐福巨峰店', '2010-02-08'); INSERT INTO t_visit (store, visit_date) VALUES ('家乐福巨峰店', '2010-02-06'); INSERT INTO t_visit (store, visit_date) VALUES ('莲花高中店', '2010-03-01');
select * from t_visit;
select a.store,a.visit_date,a.pre_visit_date,a.sequence from ( select -- rownum 判断 @pre_parent_code是否和当前的parent_code一样 ,true:让 @i+=1 false:重置@i t.*, (@i := case when @pre_parent_store = store then @i + 1 else 1 end ) sequence, (@pre_visit_date := case when @pre_parent_store=store then @pre_parent_date else 'null' end ) as pre_visit_date, -- 设置 @pre_parent_date等于上一个 visit_date (@pre_parent_date:=visit_date), -- 设置 @pre_parent_store 等于上一个 store (@pre_parent_store:=store) from (select * from t_visit order by store,visit_date) t, (SELECT @i := 0, @pre_parent_store:='') AS a group by store,visit_date order by store,visit_date desc ) a;