SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Subtract and Sum in SQL
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Nil35
Starting Member

USA
20 Posts

Posted - 07/11/2013 :  10:31:40  Show Profile  Reply with Quote

declare @a float
set @a = 100
select @a

create table #t
(id int,
colA int,
colB INT
)
insert into #t
select 1,2,4
union
select 2,4,3
union
select 3,3,2
union
select 4,5,4
union
select 5,8,1

SELECT * FROM #t


--need to create new column,
--in that in first row veriable @a - colA + ColB,
--starting from second row LAST ROW OF NEW COLUMN - colA + ColB

--second row example (fitst row of new column - colA + colB)
--third row example (second row of new comumn - colA + colB)


nil

James K
Flowing Fount of Yak Knowledge

3760 Posts

Posted - 07/11/2013 :  11:08:30  Show Profile  Reply with Quote
See the following. However, if you have a lot of rows, it is going to perform poorly. If you are on SQL 2012, there are more efficient ways:
SELECT
	t1.*,
	@a + t3.ColC AS ColC
FROM
	#t t1
	OUTER APPLY
	(
		SELECT SUM(-ColA + Colb) AS ColC
		FROM #t t2
		WHERE t2.id <= t1.ID
	) t3
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52325 Posts

Posted - 07/11/2013 :  13:15:21  Show Profile  Reply with Quote
this is another way known as quirky update



declare @a float
set @a = 100

DECLARE @ID int,@A1 int, @B1 int



CREATE CLUSTERED INDEX IDX_ID ON #t(ID)
 

SELECT TOP 1 @ID = ID,
@A1 = A,
@B1 = B
FROM #t
ORDER BY ID

UPDATE #t
SET @A =C= @A - A + B,
@ID=ID

OPTION ( MAXDOP 1)

SELECT * FROM #t




http://visakhm.blogspot.in/2010/03/using-quirky-updates-to-develop-well.html

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

James K
Flowing Fount of Yak Knowledge

3760 Posts

Posted - 07/11/2013 :  13:21:39  Show Profile  Reply with Quote
Quirky update is an undocumented feature, but as far as I can tell, it works every time without any problems (if you follow the rules). And, it is blazing fast.

Jeff Moden's article here has the rules aka ten-commandmends of quirky update http://www.sqlservercentral.com/articles/T-SQL/68467/ (look for the section Rules).
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.16 seconds. Powered By: Snitz Forums 2000