SQL LEAD -Running total

Is there any better way to get the position value without creating temporary table?
Id	value	character_Len	Position
1	ab	         2	               2
2	1	        2	               4
3	34	       2	               6
4	@	       1	                7
5	00100	 5	             12

create table #temp2 (id int , [character] varchar(100), position int)
insert into #temp2(id,character,position)
select a.Id, a.item, sum(b.lens) -1 as position
from #t1 a cross join #t2 b
where b.Id <= a.Id
group by a.Id, a.item
order by sum(b.lens)
#t1 holds all information expect position column.

Open in new window

SQL GuruAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Vitor MontalvãoMSSQL Senior EngineerCommented:
For which SQL Server version you need the solution?
Vitor MontalvãoMSSQL Senior EngineerCommented:
Well, if SQL Server 2005 or higher then you can try this:
select a.Id, a.item, sum(b.lens) -1 as Result
	RANK() OVER (PARTITION BY a.id, a.item ORDER BY sum(b.lens) -1  DESC) AS Position
from #t1 a 
	cross join #t2 b
where b.Id <= a.Id
group by a.Id, a.item
order by position

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
awking00Information Technology SpecialistCommented:
select t1.id, t1.value, len(t1.value), sum(len(t2.value)) as position
from yourtable t1, yourtable t2
where t1.id >= t2.id
group by t1.id, t1.value, len(t1.value)
order by t1.id, t1.value, len(t1.value)
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.