【SQL server】数据移动:按照日期向前移动

本文介绍了如何在SQL Server中实现数据移动,特别是当某个条件满足时(如flag设为1),如何将后续数据向前移动。操作分为三个步骤:保持2018-05-04以前数据不变,同步之后的数据,以及重新排列最后的空数据行。详细过程参考指定博客链接。
表A:
dateflagdepartmentpeople
2018-05-011Aa
2018-05-021Bb
2018-05-031Cc
2018-05-04
nullnullnull
2018-05-051Aa
2018-05-06nullnullnull
2018-05-07nullnullnull
2018-05-081Bb
2018-05-091Cc

当修改为null的flag=1 时 后面的数据前移(例如:修改2018-05-04的flag=1)

即得到表B:

dateflagdepartmentpeople
2018-05-011Aa
2018-05-021Bb
2018-05-031Cc
2018-05-04
1Aa
2018-05-051Bb
2018-05-06nullnullnull
2018-05-07nullnullnull
2018-05-081Cc
2018-05-091Aa

注意:department取自下表:(people为手动输入)

插入方法见:点击打开链接

departmentmark
A 
B 
C 


【第一步】2018-05-04以前的数据保持不变,清空需要更新的数据

--声明变量@date用来存放时间
declare @date datetime
--使变量@date的值等于表A中 flag发生变化那天的日期
select @date=date from A where flag=1 and department is null
--将表A的数据存放于临时表dep中,并且给dep加一列自增列
drop table dep
select * into dep  from A 
alter table dep add  num int  IDENTITY(1,1) NOT NULL
--将表A需要有变动的数据清空
update A set department=null,people=null where date>=@date

得到表A如下:

dateflagdepartmentpeople
2018-05-011Aa
2018-05-021Bb
2018-05-031Cc
2018-05-04
1nullnull
2018-05-051nullnull
2018-05-06nullnullnull
2018-05-07nullnullnull
2018-05-081nullnull
2018-05-091nullnull

【第二步】同步2018-05-04以及之后的数据

--创建一张新表change存放需要更新department和people的数据
drop table change
select date,department,people into change  from A where flag=1 and department is null
alter table  change  add  number  int  IDENTITY(1,1) NOT NULL
--将dep的数据同步到change后,再将change同步到A
update a set a.department=b.department,a.people=b.people from change a,dep b where a.number=b.num
update a set a.department=b.department,a.people=b.people from A a,change b where a.date=b.date

【第三步】给最后一条为空的数据重新排

详情见:https://blog.youkuaiyun.com/m0_37346566/article/details/80195424

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值