表A:
date | flag | department | people |
2018-05-01 | 1 | A | a |
2018-05-02 | 1 | B | b |
2018-05-03 | 1 | C | c |
2018-05-04 | null | null | null |
2018-05-05 | 1 | A | a |
2018-05-06 | null | null | null |
2018-05-07 | null | null | null |
2018-05-08 | 1 | B | b |
2018-05-09 | 1 | C | c |
当修改为null的flag=1 时 后面的数据前移(例如:修改2018-05-04的flag=1)
即得到表B:
date | flag | department | people |
2018-05-01 | 1 | A | a |
2018-05-02 | 1 | B | b |
2018-05-03 | 1 | C | c |
2018-05-04 | 1 | A | a |
2018-05-05 | 1 | B | b |
2018-05-06 | null | null | null |
2018-05-07 | null | null | null |
2018-05-08 | 1 | C | c |
2018-05-09 | 1 | A | a |
注意:department取自下表:(people为手动输入)
插入方法见:点击打开链接
department | mark |
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如下:
date | flag | department | people |
2018-05-01 | 1 | A | a |
2018-05-02 | 1 | B | b |
2018-05-03 | 1 | C | c |
2018-05-04 | 1 | null | null |
2018-05-05 | 1 | null | null |
2018-05-06 | null | null | null |
2018-05-07 | null | null | null |
2018-05-08 | 1 | null | null |
2018-05-09 | 1 | null | null |
【第二步】同步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