What query should I write to calculate the cumulative salary of employees from the salary table

StackOverflow https://stackoverflow.com/questions/19035738

  •  29-06-2022
  •  | 
  •  

문제

A salary table is given and we need to write a single query which prints the cumulative salary of employees. For Example:

Emp  Sal
A    10
B    15
C    20
D    5


OutPut:

Emp  Sal   Cum_Sal
A    10      10
B    15      25
C    20      45
D    5       50
도움이 되었습니까?

해결책

in some RDBMS (like PostgreSQL or SQL Server 2012 or Oracle) it's possible to use window function:

select
    Emp, Sal, sum(Sal) over(order by Emp) as Cum_Sal
from employees

if it's not possible, you can use self-join

select
    e1.Emp, e1.Sal, sum(e2.Sal) as Cum_Sal
from employees e1
    inner join employees e2 on e2.Emp <= e1.Emp
group by e1.Emp, e1.Sal

sql fiddle demo

Note that in both cases you have to define order for rolling sum (in queries above, it's ordered by Emp column).

다른 팁

For MS SQL please try this:

select NAME,SAL,sum(SAL) 
over(order by SAL rows between unbounded preceding and current row) as cum_sal 
from employee

enter image description here

select e.name,e.joining,sum(e_1.increment) from employee e inner join employee e_1 on e.name=e_1.name where e.joining>=e_1.joining group by e.name,e.joining

table is like below you can use same approach

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top