想要从以前的工资中获得加薪

时间:2019-01-03 12:33:29

标签: sql sql-server

我有这样的表结构

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

,并希望有一个额外的列来计算薪水,例如 对于第一笔记录应该是相同的,但是从第二笔记录应该是第一笔和第二笔记录的工资之和。在那种情况下,对于shweta来说,薪水是3000,对于Ankit 4500,等等。

3 个答案:

答案 0 :(得分:3)

您正在寻找累计金额。这是作为窗口功能提供的:

select t.*, sum(salary) over (order by id) as cumulative_salary
from t;

答案 1 :(得分:0)

尝试一下。 sql中的累加总和。

Select *, 
    (Select SUM(TotalSalary) 
        From Salary S2 
        Where S2.id <= S1.id)
From Salary S1

答案 2 :(得分:0)

您可以尝试以下查询

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

输出如下所示

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