现SQL2000服务器上有一张表,格式如下:
文件内容 文件组
1 A
2 A
3 A
4 B
5 C
6 D
7 E
8 E
9 F
要实现将表内容更新为:
文件内容 文件组
A
1 A
2 A
3 A
B
4 B
C
5 C
D
6 D
E
7 E
8 E
F
9 F
意思是将分组信息直接加在文件内容之中?如果不用游标,不知道如何实现这样的更新?
--> 测试数据: #tb
if object_id('tempdb.dbo.#tb') is not null drop table #tb
go
create table #tb (文件内容 varchar(1),文件组 varchar(1))
insert into #tb
select '1','A' union all
select '2','A' union all
select '3','A' union all
select '4','B' union all
select '5','C' union all
select '6','D' union all
select '7','E' union all
select '8','E' union all
select '9','F'
alter table #tb add id int
update #tb set id=b.px
from
(
select *,px=dense_rank()over( order by 文件组 )
from #tb
)b,#tb a
where a.文件内容=b.文件内容
select 文件内容,文件组,id from #tb
union all
select distinct 文件组,'',id from #tb
order by id, 文件组
文件内容 文件组 id
---- ---- -----------
A 1
1 A 1
2 A 1
3 A 1
B 2
4 B 2
C 3
5 C 3
D 4
6 D 4
E 5
7 E 5
8 E 5
F 6
9 F 6
(15 行受影响)
--> 测试数据: [tb]
if object_id('[tb]') is not null drop table [tb]
create table [tb] (文件内容 varchar(10),文件组 varchar(10))
insert into [tb]
select 1,'A' union all
select 2,'A' union all
select 3,'A' union all
select 4,'B' union all
select 5,'C' union all
select 6,'D' union all
select 7,'E' union all
select 8,'E' union all
select 9,'F'
select rn=IDENTITY(int,1,1),* into #tb from
(select * from tb
union all
select distinct '0' as 文件内容,文件组 from tb ) t order by 文件组,文件内容
select case when 文件内容='0' then 文件组 else 文件内容 end as 文件内容,
case when 文件内容='0' then '' else 文件组 end as 文件组 from #tb