Development

SQL Server – Methods to find running totals of a column

HI friends, in some working scenario or during interviews we got the task to find the running totals of a column. In this blog I have listed few methods which may help you in determining running totals:

Let’s first create a test table and insert some data into it.

Create table #t1 (ID int)

GO

INSERT INTO #t1 values (1), (2), (3)

GO

–Method 1

SELECT ID, SUM(ID) OVER(Order by ID  ROWS BETWEEN unbounded preceding

and current row) run_tot

FROM #t1

–Method 2

SELECT  A.ID,SUM(B.ID) run_tot

FROM #t1 A

JOIN #t1 B ON B.id <= A.id

GROUP BY A.ID

Running_Totals

You will get the same output from Method 1 and Method 2.

That’s all folks for the day. Have a good day!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s