postgresql - 组内的 MIN 记录
问题描述
我想user_id
根据created_at
时间戳获取 MIN step per 的记录。
样本数据:
+---------+-------+---------------------+
| user_id | step | created_at |
+---------+-------+---------------------+
| 7bc6de | step1 | 2021-03-16 14:03:16 |
| 7bc6de | step2 | 2021-03-16 14:04:07 |
| 7bc6de | step2 | 2021-03-16 14:03:47 |
| 7bc6de | step3 | 2021-03-16 14:03:55 |
| 7bc6de | step3 | 2021-03-16 14:04:00 |
| 7bc6de | step1 | 2021-03-16 14:04:02 |
| 7bc6de | step2 | 2021-03-16 14:03:16 |
| 7bc6de | step3 | 2021-03-16 14:04:07 |
| 7bc6de | step4 | 2021-03-16 14:04:08 |
| 7bc6de | step4 | 2021-03-16 14:04:09 |
+---------+-------+---------------------+
所需的输出:
+---------+-------+---------------------+
| user_id | step | created_at |
+---------+-------+---------------------+
| 7bc6de | step1 | 2021-03-16 14:03:16 |
| 7bc6de | step2 | 2021-03-16 14:03:16 |
| 7bc6de | step3 | 2021-03-16 14:03:55 |
| 7bc6de | step4 | 2021-03-16 14:04:08 |
+---------+-------+---------------------+
解决方案
这是 PostgreSQL 扩展的一个例子DISTINCT ON
:
SELECT DISTINCT ON (user_id, step)
user_id, step, created_at
FROM atable
ORDER BY user_id, step, created_at;
推荐阅读
- reactjs - 当我将 Alerts 组件导入 App.js 时,出现以下错误
- sockets - 在 Python 中对 UDP 数据报做出反应的最快方法是什么?
- spring-boot - How to add default logback.xml to spring boot project?
- javascript - Only js file per page in laravel
- spring-boot - Object not returned to caller as expected during exception in camel route
- java - Best way to secure Spring Boot & Angular app with SSL
- django - how to get access to the django class object
- r - Launching Rattle
- angular - Angular 11:通过管道过滤对象列表和对象列表
- r - R styler addin: how to setup?