SQL 中的第一个值和倒数第二个值

问题描述 投票:0回答:1

我有一个包含 4 列的表:worker_id、month、basic_salary。 我正在尝试编写一个脚本,返回worker_id、最后工资日期、倒数第二个basic_salary日期、最后工资金额(来自basic_salary列)。

这是我写的脚本:

with cte as (
select WORKER_ID,  (select max(month) from workers_table) last_salary
,ROW_NUMBER()over (partition by worker_id order by month) rn
from workers_table
group by WORKER_ID,month
)
select * from cte 
where rn=2

这是数据示例:

enter image description here

我得到的数据是:

WORKER_ID   last_salary rn
2011-11-11  2022-01-04  2
2011-11-12  2022-01-04  2
2011-11-13  2022-01-04  2
2011-11-14  2022-01-04  2
2011-11-15  2022-01-04  2
2011-11-16  2022-01-04  2

last_salary 列不正确,我找不到修复它并获得正确结果的方法。

sql sql-server aggregate-functions window-functions
1个回答
0
投票

尝试如下所示。获取您的

cte
并且不要使用
GROUP BY
。从
cte
开始,具有自连接条件,第一个具有
rn = 1
,第二个具有
rn = 2
。更新
SELECT
声明。请检查以下查询。

;WITH cte AS (
    SELECT WORKER_ID,
           month,
           basic_salary,
           ROW_NUMBER() OVER (PARTITION BY worker_id ORDER BY month) AS rn
    FROM WORKERS_TABLE
)
SELECT c1.WORKER_ID,
       c1.month AS LastSalaryDate,
       c1.basic_salary As Last_basic_salary,
       c2.month AS SecondLastSalaryDate 
FROM cte c1
    JOIN cte c2 ON c1.WORKER_ID = c2.WORKER_ID
WHERE c1.rn = 1 AND c2.rn = 2
© www.soinside.com 2019 - 2024. All rights reserved.