两行合并成一行的问题
现有一个表 t_a
字段:
col001,col002,col003,id(自增列)
值:
null, null, aaa, 1 (只有col003有值,其他列都是null值)
11, 232, null, 2 (只有col003为null,其他列都有值)
null, null, bbb, 3 (只有col003有值,其他列都是null值)
13, 33, null, 4 (只有col003为null,其他列都有值)
。。。。。。
想把前一个的col003写入后一行的col003值中,这样两行就能合成一行,然后把前一行删掉就行了
结果如下:
11,232,aaa, 2
13, 33 , bbb ,4
求教这个sql该如何写?
非常感谢
[解决办法]
--这样?
update t_a set col003=(select top 1 col003 from t_a where id=t.id-1)
from t_a as t
where id % 2=0
[解决办法]
create table #t_a(col001 int,col002 int,col003 varchar(100),id int identity(1,1))
insert into #t_a select null, null, 'aaa '
insert into #t_a select 11, 232, null
insert into #t_a select null, null, 'bbb '
insert into #t_a select 13, 33, null
--更新
update #t_a set col003=(select top 1 col003 from #t_a where id=t.id-1)
from #t_a as t
where id % 2=0
--删除
delete #t_a where id % 2 =1
select * from #t_a
drop table #t_a
[解决办法]
create table t_a(col001 int,col002 int,col003 varchar(10),id int)
insert into t_a select null, null, 'aaa ',1
insert into t_a select 11, 232, null, 2
insert into t_a select null, null, 'bbb ',3
insert into t_a select 13, 33, null, 4
go
select
a.col001,a.col002,b.col003,a.id
from
(select (select count(*) from t_a where id <=m.id and col003 is null) as nid,* from t_a m where m.col003 is null) a,
(select (select count(*) from t_a where id <=m.id and col001 is null) as nid,* from t_a m where m.col001 is null) b
where
a.nid=b.nid
go
/*
col001 col002 col003 id
----------- ----------- ---------- -----------
11 232 aaa 2
13 33 bbb 4
*/
drop table t_a
go
[解决办法]
以上SQL针对id字段不连续的情况。
[解决办法]
update t_a set col003=b.col003
from t_a inner join t_a b on b.id=id+1
where id % 2=0
[解决办法]
更正我前面写的
1、
update a set a.col003=b.col003
from t_a a inner join t_a b on b.id=a.id-1
where a.id % 2=0
2、
delete from t_a where where a.id % 2=1
[解决办法]
update t_a
set col003 = b.col003 from t_a,t_a b
where test.id%2 = 0 and (test.id = b.id +1)
delete t_a where id % 2 =1
[解决办法]
update t_a
set col003 = b.col003 from t_a,t_a b
where t_a.id%2 = 0 and (t_a.id = b.id +1)
delete t_a where id % 2 =1