Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Resetting an Incremental Update 1

Status
Not open for further replies.

dukeslater

Technical User
Jan 16, 2001
87
US
I've inserted records into a temp table in the specific order they need to be sequenced:

visit sequence
100
100
100
200
200
300
400

What is the most efficient way to update the sequence so that it resets at each change of visit?

visit sequence
100 1
100 2
100 3
200 1
200 2
300 1
400 1


Thanks....


 
SQL Server 2000 or 2005?

------
[small]select stuff(stuff(replicate('<P> <B> ', 14), 109, 0, '<.'), 112, 0, '/')[/small]
[banghead]
 
Probably the simplest way is about ordered insert into temp table with identity. Method itself is handy but somewhat dirty... if everything works OK, fine.

Suppose this is source table:
Code:
create table srcData( visit int )
insert into srcData 
select 100 union all
select 100 union all
select 100 union all
select 200 union all
select 200 union all
select 300 union all
select 400
Ordered insert is done this way:

Code:
select identity(int, 1, 1) as globalseq, visit, convert(smallint, null) as sequence
into #tmp
from srcData
order by visit
option (maxdop 1) -- SMP = bad

select * from #tmp
Now based on global sequence it is easy to calculate sequence per visit:
Code:
update T
set sequence = globalseq - minseq + 1
from #tmp T
inner join
(	select visit, min(globalseq) as minseq
	from #tmp
	group by visit
) TG
on T.visit = TG.visit

select * from #tmp
order by visit, sequence

------
[small]select stuff(stuff(replicate('<P> <B> ', 14), 109, 0, '<.'), 112, 0, '/')[/small]
[banghead]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top