基于年份的汇总

时间:2014-10-21 13:48:27

标签: sql oracle aggregate

我有一个表格X,我从中选择四列作为我计算的子集。以下是仅一名员工的示例数据集。

Date_key    Emp_num Salary  Bonus                                       
201001      54343    543    50                                      
201002      54343    453    50                                      
201101      54343    453    100                                     
201106      54343    765    50                                      
201208      54343    777    100 

如果我想找出平均员工工资和奖金..我可以写一个查询,让我在一段时间内为员工提供平均值。

select date_key,emp_num,avg(salary),avg(bonus) group by date_key,emp_num ..

但是我想找到1年,2年,3年...... 10年薪水的平均值。但是,我自己也无法达到预期的效果。结果数据集看起来应该是这样的;

Emp_num Avg(salary)-2008    Avg(Bonus)-2008 Avg(salary)-2008&2009   Avg(Bonus)-2008&2009    Avg(salary)-2008 to 2010    Avg(Bonus)-2008 to 2010 Avg(salary)-2008 to 2011    Avg(Bonus)-2008 to 2011 Avg(salary)-2008 to 2012    Avg(Bonus)-2008 to 2012
54343   0   0   0   0   498 50  553.5   62.5    598.2   70

2 个答案:

答案 0 :(得分:2)

我有一个解决方案,可以在列中显示结果,也许你可以把它包起来。

with t as
  (select Emp_num, substr(date_key,1,4) as year, 
    avg(salary) over (partition by Emp_num order by Date_key rows unbounded preceding) as avg_sal,
    avg(bonus) over (partition by Emp_num order by Date_key rows unbounded preceding) as avg_bon,
    row_number() over (partition by Emp_num, substr(date_key,1,4) order by Date_key desc) as R
  from Table1)
select EMP_NUM, YEAR, AVG_SAL, AVG_BON
from t
where R = 1;


EMP_NUM     YEAR    AVG_SAL     AVG_BON
-------------------------------------------
54343       2010    498         50
54343       2011    553.5       62.5
54343       2012    598.2       70

参见示例SQLFiddle

答案 1 :(得分:1)

要制作这些列,您必须事先了解这些年份:

select 
  emp_num,
  avg(case when substr(Date_key,1,4) = '2008' then salary end) as avg_salary_2008,
  avg(case when substr(Date_key,1,4) = '2008' then bonus end) as avg_bonus_2008,
  avg(case when substr(Date_key,1,4) between '2008' and '2009' then salary end) as avg_salary_2008to2009,
  avg(case when substr(Date_key,1,4) between '2008' and '2009' then bonus end) as avg_bonus_2008to2009,
  avg(case when substr(Date_key,1,4) between '2008' and '2010' then salary end) as avg_salary_2008to2010,
  avg(case when substr(Date_key,1,4) between '2008' and '2010' then bonus end) as avg_bonus_2008to2010,
  avg(case when substr(Date_key,1,4) between '2008' and '2011' then salary end) as avg_salary_2008to2011,
  avg(case when substr(Date_key,1,4) between '2008' and '2011' then bonus end) as avg_bonus_2008to2011,
  avg(case when substr(Date_key,1,4) between '2008' and '2012' then salary end) as avg_salary_2008to2012,
  avg(case when substr(Date_key,1,4) between '2008' and '2012' then bonus end) as avg_bonus_2008to2012
from employees
group by emp_num;

(如果您事先不知道这些年份,您仍然可以先选择年份,然后动态构建您的查询。)