-5

I have table structure like this

id  name    salary  manager
1   vishal  1000    Shiva
2   shweta  2000    ABC
3   Ankit   1500    Navodit
4   Smriti  1900    Navodit
5   Shiva   1100    Santosh
6   Navodit 2800    Santosh

and want an additional column which calculates the salary like for first record it should be same.but from second record it should be the addition of first and second record salary. in that case for shweta the salary would be 3000,for Ankit 4500 and so on.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
  • 1
    Your question is being downvoted as you've not shown any attempts or research. Before posting a question, please do take the time to try to solve the problem yourself and do some research. There are 100's of resources out there on how to get a cumulative sum in SQL Server, and I'm sure a search on your favourite search engine would have yielded you with the result you wanted. Stack Overflow isn't a free coding service, and the vounteers here expect you to put the effort into answering your own question before you ask them for help, or to do it for you (for free). Thanks. – Thom A Jan 03 '19 at 12:44
  • 2
    Possible duplicate of [How to get cumulative sum](https://stackoverflow.com/questions/2120544/how-to-get-cumulative-sum) – jned29 Jan 03 '19 at 12:58

3 Answers3

3

You are looking for a cumulative sum. This is provided as a window function:

select t.*, sum(salary) over (order by id) as cumulative_salary
from t;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Trying it on my end. The cumulative sum in sql will do.

Select *, 
    (Select SUM(TotalSalary) 
        From Salary S2 
        Where S2.id <= S1.id)
From Salary S1
jned29
  • 477
  • 12
  • 50
0

You can try the following query

create table #Salary (id int, name varchar(20), salary int, manager varchar(20))
insert into #Salary values (1,   'vishal',  1000,   'Shiva'),
(2,   'shweta',  2000,    'ABC'),
(3,   'Ankit',   1500,    'Navodit'),
(4,   'Smriti',  1900,    'Navodit'),
(5,   'Shiva',   1100,    'Santosh'),
(6,   'Navodit', 2800,    'Santosh')

select t1.id, t1.name, t1.salary, SUM(t2.salary) as [SumSal]
from #Salary t1
inner join #Salary t2 on t1.id >= t2.id
group by t1.id, t1.name, t1.salary
order by t1.id

The output is as shown below

id  name    salary  SumSal
--------------------------
1   vishal  1000    1000
2   shweta  2000    3000
3   Ankit   1500    4500
4   Smriti  1900    6400
5   Shiva   1100    7500
6   Navodit 2800    10300
Suraj Kumar
  • 5,547
  • 8
  • 20
  • 42