我有一张表,比方说emp_sal,我想要找出员工的3rd record,基于descending orderchange_date.

但问题是对于很少的员工,只有不到三条记录,对于这样的员工,我需要第二条(如果表中有两行该员工)或第一条(如果表中只有一条记录)记录.

emp_sal table with data:

empid change_date salary
1 2023-01-01 1000
1 2023-02-01 1400
1 2023-03-01 1450
1 2023-04-01 1500
2 2023-11-01 2500
2 2023-12-01 2400
2 2023-12-15 2200
3 2023-05-01 500
3 2023-06-01 640
4 2023-10-01 3000

我试着使用ROW_NUMBER,但无法获得少于3条记录的记录.

select * from 
(select e.*, row_number() over (partition by empid order by change_date desc) as rn
  from emp_sal e)
where rn = 3; -- what other condition is needed here, I am not sure

Expected output:

empid change_date salary
1 2023-02-01 1400
2 2023-11-01 2500
3 2023-05-01 500
4 2023-10-01 3000

我们将非常感谢您的帮助.如果需要更多细节,请让我知道.

推荐答案

如果在内部查询中添加count(*) over (partition by empid) cnt,则可以将筛选器设置为where rn = least(3, cnt).

select s.empid, s.change_date, s.salary
from (
    select
        e.*,
        row_number() over (partition by e.empid order by e.change_date desc) as rn,
        count(*) over (partition by e.empid) as cnt
    from emp_sal e
) s
where s.rn = least(3, s.cnt)
order by s.empid;

请参见this db<>fiddle.

Sql相关问答推荐

提取Snowflake SQL中的嵌套键

如何将多个 Select 查询从一个表中组合出来

将SEMI JOIN、ANTI JOIN转换为非连接SQL

如何通过比较不同表中相同ID S的值来筛选ID为S的列表?

如何从多行数据中获取一行合并数据?

了解放置时的连接

PostgreSQL 9.6嵌套的INSERT/RETURN语句的CTE性能低得令人无法接受

找到最新的连线

在查询Oracle SQL中创建替代ID

我可以在SQLite3中使用BLOB作为主键吗?

使用SQL数据库中的现有列派生或修改几个列

不存在记录的国外关键点

验证某个日期前后的连续代码

BigQuery导航函数计算ID

一次 Select 语句中按组累计的SQL累计数

在 MS Access VBA 中,如何测量显示查询的时间?

如何在 ClickHouse SQL 中使用 CTE 将邻居语句中的数字作为偏移量传递?

如何更改 duckdb R 中的数据约束

T-SQL 查询计算日期在其他列中定义的日期之间绑定的行数

Select 随机行,使得列子组的组合是唯一的