Cumulative Calculation - Based on Sample Data

梦想与她 提交于 2021-01-20 12:43:54

问题


1

Hi I am providing Sample Data below: Based on Sample data I want result output as per screenshot ..

create table mytable 
(
    emp_name varchar2(50)
    ,dept_number number
    ,Salary number
    ,Calendar_Year number
    ,Calendar_Period number
);

insert into mytable values ('Bob',6620,6500,2020,1);
insert into mytable values ('Bob',6620,1500,2020,1);
insert into mytable values ('Rachel',6620,3400,2020,1);
insert into mytable values ('Nancy',6620,1400,2020,1);
insert into mytable values ('Rachel',6620,4500,2020,2);
insert into mytable values ('Nancy',6620,2300,2020,2);
insert into mytable values ('Nancy',6620,1500,2020,3);
insert into mytable values ('Bob',6640,1200,2020,1);
insert into mytable values ('Bob',6640,1000,2020,1);
insert into mytable values ('Rachel',6640,1500,2020,1);
insert into mytable values ('Nancy',6640,1000,2020,1);
insert into mytable values ('Rachel',6640,4500,2020,2);
insert into mytable values ('Nancy',6640,1100,2020,2);
insert into mytable values ('Nancy',6640,1500,2020,3);

回答1:


Hmmm . . . You seem to want to expand the rows and then take the most recent salary if it is not available:

select emp_name, dept_number, calendar_year, calendar_period,
       coalesce(sum(t.salary),
                lag(sum(t.salary) ignore nulls) over (partition by emp_name order by calendar_year, calendar_period)
                ) as salary
from (select distinct emp_name, dept_number from mytable) ed cross join
     (select distinct calendar_year, calendar_period from mytable) yp left join
     mytable t
     using (emp_name, dept_number, calendar_year, calendar_period)
group by emp_name, dept_number, calendar_year, calendar_period
order by calendar_year, calendar_period, dept_number, emp_name

Here is a db<>fiddle.




回答2:


seems like what Gordon provided is correct except you want to calculate lag() by emp_name and dept_number

select emp_name, dept_number, calendar_year, calendar_period,
       coalesce(sum(t.salary),
                lag(sum(t.salary) ignore nulls) over (partition by emp_name,dept_number order by calendar_year, calendar_period)
                ) as salary
from (select distinct emp_name, dept_number from mytable) ed cross join
     (select distinct calendar_year, calendar_period from mytable) yp left join
     mytable t
     using (emp_name, dept_number, calendar_year, calendar_period)
group by emp_name, dept_number, calendar_year, calendar_period
order by dept_number
         , Calendar_Period
         , emp_name


来源:https://stackoverflow.com/questions/65513106/cumulative-calculation-based-on-sample-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!