组内MIN记录

MIN record within a group

我想根据 created_at 时间戳获取每个 user_id 的 MIN 步数记录。

样本数据:

+---------+-------+---------------------+
| 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;