需求:对表t_employee_apply表进行时间排序,按照年月日和相同年月日的顺序进行新字段赋值 即新字段值为:YGD+yyyyMMdd+分组排序号(不足五位用0补齐)
数据库表结构和记录如下:
第一次sql只是 定义了变量,获取总的排序号,但是没有分组,sql如下:
select
@r:=@r+1 as row_num
,id,date_format(c_time, '%Y%m%d') as ctime,c_time,concat('YGD',date_format(c_time, '%Y%m%d')) as apply_no
from t_employee_apply,(select @r:=0) b
order by c_time asc;
改进后的SQL如下:
select
id,concat('YGD',ctime,lpad(cast((groupRow) AS CHAR),5,0)) as apply_no
from (
select
@group_row:=CASE when @ctime=a.ctime then @group_row+1 else 1 end as groupRow,
@ctime:=a.ctime as ctime,
a.c_time,a.id
from
(
select
id,date_format(c_time, '%Y%m%d') as ctime,c_time
from t_employee_apply
)a ,(select @group_row:=1, @ctime:='') as b
ORDER BY a.ctime asc, a.c_time asc
) b
现在结果就很完美了,最后执行更新插入sql:
update
t_employee_apply app ,
(
select
id,concat('YGD',ctime,lpad(cast((groupRow) AS CHAR),5,0)) as apply_no
from (
select
@group_row:=CASE when @ctime=a.ctime then @group_row+1 else 1 end as groupRow,
@ctime:=a.ctime as ctime,
a.c_time,a.id
from
(
select
id,date_format(c_time, '%Y%m%d') as ctime,c_time
from t_employee_apply
)a ,(select @group_row:=1, @ctime:='') as b
ORDER BY a.ctime asc, a.c_time asc
) b
) cc set app.apply_no = cc.apply_no where app.id = cc.id;