Calculate Running Total in Sql Server

In this article we will talk about how to calculate running total in SQL SERVER. Now a day it is very tricky question asked by interviewer for experienced or fresher.




Let’s start it practically. Create a database

CREATE DATABASE Demo

Now create a table, query for create a data table.

CREATE TABLE Employee
(
 Id INT,
Name NVARCHAR(100),
Salary INT
)

Now press F5 for execute this query, after execute this query Employee table is created successfully.

Now insert records in this (Employee) table.

Insert into Employee values(1,'Rahul',22000), (2,'Raj',15000), (3, 'Aman',12000), (4,'Abhishek',9000)
Select above query and execute it. It means all these records are inserted in Employee table which you can see.

SELECT * FROM Employee

Employee Table Data

Now come on the point for Calculate Running Total.

Question: What do you mean by Calculate Running Total?

Answer: In Employee table there are only 3 columns (Id, Name, Salary) add one extra column (which is Running Total) and this column contains values for Rahul 22000 but it contains Running Total for Raj 37000 ( Rahul + Raj ) in this series for Aman 49000(37000+12000) etc.

Now implement this logic in SQL Server, query for it.

SELECT EMP.ID, EMP.NAME , EMP.SALARY,
(SELECT SUM (employee.SALARY) FROM EMPLOYEE employee 
WHERE employee.ID <=EMP.ID) AS 'RUNNING TOTAL SALARY'
FROM EMPLOYEE EMP

Output:


Calculate Running Total 

If you want to take it power point slide then download it from github.

Download Running PPT Slide


Download it from youtube.


Conclusion: In this article we saw that how to calculate running total in Sql server in easy way.

No comments

Powered by Blogger.