最后两个日期之间的薪金增长

时间:2019-04-25 06:45:35

标签: sql postgresql date

我正在尝试解决此问题:

  • 找到最近的两个最后日期之间的工资增长(百分比),并按每位员工的增长对结果进行排名。

我已经尝试过了:

SELECT employee, salary AS second_salary
FROM salary
INNER JOIN salary sal
ON (sal.paydate = (SELECT salary FROM salary WHERE paydate = (SELECT MAX(paydate) FROM salary)) AND sal.employee = salary.employee)
WHERE date = (
    SELECT MAX(paydate) FROM salary WHERE paydate <> (
        SELECT MAX(paydate) FROM salary))

但这不起作用

|  paydate   | salary | employee  |
|------------|--------|-----------|
| 2015-05-15 |   1000 |         1 |
| 2015-04-15 |   1250 |         1 |
| 2015-03-15 |    800 |         1 |
| 2015-02-15 |   3000 |         1 |
| 2015-05-15 |    500 |         2 |
| 2015-04-15 |   1500 |         2 |
| 2015-03-15 |   2500 |         2 |
| 2015-02-15 |   3000 |         2 |
| 2015-05-15 |    400 |         3 |
| 2015-04-15 |    582 |         3 |
| 2015-03-15 |    123 |         3 |
| 2015-02-15 |    659 |         3 |

我想获得按增长率排序的最后两个薪水之间的百分比增长率。

3 个答案:

答案 0 :(得分:1)

首先:我建议您阅读PostgreSQL文档中有关窗口函数的内容。 (https://www.postgresql.org/docs/current/tutorial-window.html

第二个:这是另一个可以工作的代码版本:

with cte as
(
    select 
        *
        , dense_rank() over (order by paydate desc) as ranker
        , lag(salary) over (partition by employee order by paydate desc) as previous_salary
    from salary
)
select 
    employee
    , cast(((salary - previous_salary) * 100) / previous_salary as varchar)||' %' as PayGrowth
    --, * -- uncomment if you want to understand a little better the window mechanism.
from cte
where ranker = 2
order by employee, paydate;

结果:

employee  PayGrowth
1         25 %
2         200 %
3         45 %

答案 1 :(得分:0)

您可以使用lag Windows分析功能

with salary( paydate, salary, employee) as
(    
 select '2015-05-15',1800,1  union all
 select '2015-04-15',1600,1  union all
 select '2015-03-15',1300,1  union all   
 select '2015-02-15',1000,1  
)    
select s.paydate,s.salary, 
       round(100*(cast(s.salary-lag(s.salary,1,s.salary) 
                  over (partition by s.employee order by s.paydate) as decimal)
             /lag(s.salary,1,s.salary) over (partition by s.employee order by s.paydate)
              ,2) as growth_as_percentage  
  from salary s
 order by s.employee, s.paydate desc;

paydate     salary  growth_as_percentage
2015-05-15  1800    12,5000
2015-04-15  1600    23,0800
2015-03-15  1300    30
2015-02-15  1000    0 

Demo

答案 2 :(得分:0)

我在子查询中使用了RANK()和LEAD()窗口函数来获取更改和更改索引,然后在每个员工的主查询中选择了最后更改

SELECT employee, paydate, change
FROM (
    SELECT employee, paydate,
        RANK() OVER (PARTITION BY employee ORDER BY paydate DESC) as rnk,
        (salary - LEAD(salary) OVER (PARTITION BY employee ORDER BY paydate DESC)) * 100.0 / salary as change
    FROM salary) w
WHERE rnk = 1
ORDER BY change DESC

输出

employee    paydate     change
1           2015-05-15  -25.0000000000000000
3           2015-05-15  -45.5000000000000000
2           2015-05-15  -200.0000000000000000