表table1
字段:nbxh varchar(18),bgcs int ,hzrq datetime现在bgcs没有,根据核准日期hzrq, 确定bgcs,相同nbxh的hzrq最小的一条bgcs为0,第二小的为1,依次类推..如果hzrq一样前后顺序任意。--update 前
nbxh bgcs hzrq
0001 2001-02-01
0001 2001-02-01
0001 2008-03-01
0001 2001-01-01
0002 2001-01-01
0002 2011-01-01
0002 2009-02-01--update 后
nbxh bgcs hzrq
0001 2 2001-02-01
0001 1 2001-02-01
0001 3 2008-03-01
0001 0 2001-01-01
0002 0 2001-01-01
0002 2 2011-01-01
0002 1 2009-02-01
字段:nbxh varchar(18),bgcs int ,hzrq datetime现在bgcs没有,根据核准日期hzrq, 确定bgcs,相同nbxh的hzrq最小的一条bgcs为0,第二小的为1,依次类推..如果hzrq一样前后顺序任意。--update 前
nbxh bgcs hzrq
0001 2001-02-01
0001 2001-02-01
0001 2008-03-01
0001 2001-01-01
0002 2001-01-01
0002 2011-01-01
0002 2009-02-01--update 后
nbxh bgcs hzrq
0001 2 2001-02-01
0001 1 2001-02-01
0001 3 2008-03-01
0001 0 2001-01-01
0002 0 2001-01-01
0002 2 2011-01-01
0002 1 2009-02-01
from tb a
insert into tb select '0001',null,'2001-02-01'
insert into tb select '0001',null,'2001-02-01'
insert into tb select '0001',null,'2008-03-01'
insert into tb select '0001',null,'2001-01-01'
insert into tb select '0002',null,'2001-01-01'
insert into tb select '0002',null,'2011-01-01'
insert into tb select '0002',null,'2009-02-01'
go
select nbxh,ROW_NUMBER()over(partition by nbxh order by hzrq)-1 bgcs,hzrq into tb_temp from tb
go
drop table tb
go
exec sp_rename 'tb_temp','tb'
select * from tb
/*
nbxh bgcs hzrq
---------- -------------------- -----------------------
0001 0 2001-01-01 00:00:00.000
0001 1 2001-02-01 00:00:00.000
0001 2 2001-02-01 00:00:00.000
0001 3 2008-03-01 00:00:00.000
0002 0 2001-01-01 00:00:00.000
0002 1 2009-02-01 00:00:00.000
0002 2 2011-01-01 00:00:00.000(7 行受影响)
*/
go
drop table tb
如果遇到hzrq相同的怎么办呢
如果hzrq相同的话,那么两个的bgcs就一样了
from tb a
还是不行哦,hzrq=a.hzrq 时候count(distinct hzrq)还是=0.
是这样,我现在不能确定其他那些字段不一样,随机的,也有可能完全一样,完成后表的主键应该是nbxh+bgcs。另外我用的Sybase,,ROW_NUMBER()函数好像没有。有没有一个SQL语句搞定的那种,谢谢~
go
update a set bgcs=(select count(*) from tb where nbxh=a.nbxh and hzrq<a.hzrq and col < a.col)
from tb a
alter table tb drop column col
go
这样每次排个序都要改两次表结构,还不如你就把 newid() 放在表里,就拿它当唯一列算了!
说来话就长了,我把数据从一个系统迁移到另一个系统,原来本来有UUid做主键的,客户比较变态,非要按照nbxh+bgcs的模式重新做主键,按照hzrq排序,不然他们的系统不认。