如何按列值筛选并提取runs表中各组最新记录(SQL需求)
提取每个
input与type组合的最新记录SQL实现 原数据表结构与数据
runs表的结构和数据如下:
| id | job_id | command_id | type | input | created_at |
|---|---|---|---|---|---|
| 875 | 61 | 25 | Pre | show name | 2022-08-08 07:36:14 |
| 876 | 61 | 26 | Pre | show dob | 2022-08-08 07:36:18 |
| 877 | 61 | 25 | Post | show name | 2022-08-08 07:37:00 |
| 878 | 61 | 26 | Post | show dob | 2022-08-08 07:37:03 |
| 879 | 61 | 25 | Post | show name | 2022-08-10 00:18:25 |
| 880 | 61 | 25 | Post | show name | 2022-08-10 00:20:27 |
| 891 | 61 | 26 | Post | show dob | 2022-08-10 00:20:30 |
需求说明
需在以下筛选条件下,提取每个input与type组合对应的最新记录:
job_id = 61type in ("Pre", "Post")input in ("show name", "show dob")
预期查询结果
| id | job_id | command_id | type | input | created_at |
|---|---|---|---|---|---|
| 875 | 61 | 25 | Pre | show name | 2022-08-08 07:36:14 |
| 876 | 61 | 26 | Pre | show dob | 2022-08-08 07:36:18 |
| 880 | 61 | 25 | Post | show name | 2022-08-10 00:20:27 |
| 891 | 61 | 26 | Post | show dob | 2022-08-10 00:20:30 |
解决方案
使用窗口函数ROW_NUMBER()可以高效实现需求,具体SQL语句如下:
SELECT id, job_id, command_id, type, input, created_at FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY input, type ORDER BY created_at DESC) AS rn FROM runs WHERE job_id = 61 AND type IN ('Pre', 'Post') AND input IN ('show name', 'show dob') ) t WHERE rn = 1;
思路说明
- 内层子查询:先筛选出符合条件的记录,再通过
PARTITION BY input, type将数据按input和type的组合分组,每组内按created_at降序排序,用ROW_NUMBER()给每组内的记录编号,最新的记录编号为1。 - 外层查询:直接筛选出编号为1的记录,即为每个组合的最新记录。
如果存在多条记录created_at完全相同的情况,若需保留所有这些最新记录,可将ROW_NUMBER()替换为RANK()或DENSE_RANK()。
内容的提问来源于stack exchange,提问作者JuniorDev
相关产品推荐
相关产品推荐

