我有一表 stdata有3个字段为:
自增字段: ID
char(21):stdata
int: num
现在表里有记录,num值都为空值。
需求:将stdata相同的记录筛选出来(即:group by stdata having count(stdata)>1)
后,将num修改为1、2、3...n,n为相同stdata的记录数。
谢谢!
...全文
25211打赏收藏
紧急求助:用sql语句如何实现如下功能?
我有一表 stdata有3个字段为: 自增字段: ID char(21):stdata int: num 现在表里有记录,num值都为空值。 需求:将stdata相同的记录筛选出来(即:group by stdata having count(stdata)>1) 后,将num修改为1、2、3...n,n为相同stdata的记录数。 谢谢!
if (exists (select * from sysobjects where name='temptale'))
drop table temptale
select id,stdata,IDENTITY(int, 1,1) as num into temptale from lstable
where stdata in (select stdata from lstable group by stdata having count(stdata)>=2)
order by stdata,macid
update lstable set num=temptale.num from temptale where lstable.macid=temptale.macid
/*----主语句---*/
update @t1 set num=new_num
from
(
select [new_num]=
(select count(1) from (select * from @t1 where stdata in (
select stdata from @t1 group by stdata having count(stdata)>=2
)) a where a.stdata=b.stdata and a.id<=b.id),*
from
(select * from @t1 where stdata in (select stdata from @t1 group by stdata having count(stdata)>=2)) b
) a,@t1 b where a.id=b.id
create table a ----测试数据生成
(id int identity(1,1),stdata char(21),num int)
insert into a select '1',null
insert into a select '1',null
insert into a select '1',null
insert into a select '7',null
insert into a select '2',null
insert into a select '3',null
insert into a select '3',null
insert into a select '3',null
insert into a select '4',null
insert into a select '2',null
declare -------双游标判断输入NUM
@a char(21),
@b char(21),
@c int,
@num int
declare x cursor for
select stdata
from a
group by stdata
having count(stdata)>=2
open x
fetch next from x
into @a
while(@@fetch_status=0)
begin
set @num=1
declare y cursor for
select id,stdata from a where stdata=@a
open y
fetch next from y into @c,@b
while(@@fetch_status=0)
begin
update a
set num=@num
where id=@c
set @num=@num+1
fetch next from y into @c,@b
end
close y
deallocate y
fetch next from x
into @a
end
close x
deallocate x
/*----主语句---*/
update @t1 set num=new_num
from
(
select [new_num]=
(select count(1) from
(select stdata from @t1 group by stdata having count(stdata)>=2) a
where a.stdata<=b.stdata),stdata
from
(select stdata from @t1 group by stdata having count(stdata)>=2) b
) a,@t1 b where a.stdata=b.stdata
update stdata
set num=t.c1
from
(select a.stdata,count(*) as c1 from stdata a
where a.id<b.id
group by stdata
having count(stdata)>1) b
where stdata.stdata=b.stdata
try:
update stdata from (select stdata,count(*) as dd from stdata group by stdata having count(stdata)>1) rr set num=rr.dd where stdata.stdata=rr.stdata