Thursday, 26 November 2020

Running total in SQL

CREATE TABLE #Employee(Id INT IDENTITY,Name VARCHAR(100), Salary money)
 
INSERT INTO #Employee(Name, Salary)VALUES('Ram',50000)
INSERT INTO #Employee(Name, Salary)VALUES('Shyam',40000)
INSERT INTO #Employee(Name, Salary)VALUES('Ghanshyam',40000)
INSERT INTO #Employee(Name, Salary)VALUES('Sita',30000)
INSERT INTO #Employee(Name, Salary)VALUES('Gita',20000)
INSERT INTO #Employee(Name, Salary)VALUES('Pranita',1000)
 
SELECT * FROM #Employee


 














SELECT *, SUM(Salary) OVER(ORDER BY Id) AS 'Running Total' FROM #Employee


 













SELECT e1.*,(SELECT SUM(Salary) FROM #Employee e2 WHERE e1.id >= e2.id) AS 'Running Total' 
FROM #Employee e1



















--Note - For Running total, required column each row value must be unique. In OVER () clause or WHERE clause.


No comments:

Post a Comment