【发布时间】:2021-12-31 00:21:09
【问题描述】:
假设我有一个这样的 SQL 表:
| serial(pk) | name | status | location | time_updated |
|---|---|---|---|---|
| 1 | 'joe' | 'at_home' | 'USA' | 01:30 |
| 2 | 'jane' | 'at_store' | 'USA' | 02:30 |
| 3 | 'joe' | 'driving' | 'USA' | 12:15 |
| 4 | 'joe' | 'driving' | 'USA' | 13:30 |
| 5 | 'joe' | 'at_store' | 'USA' | 15:00 |
| 5 | 'joe' | 'at_store' | 'USA' | 15:15 |
| 6 | 'joe' | 'driving' | 'USA' | 16:00 |
| 7 | 'joe' | 'driving' | 'USA' | 17:10 |
| 8 | 'joe' | 'at_home' | 'USA' | 20:00 |
在这个表中可以有三种不同的状态':“at_home”、“at_store”和“driving”。
我想要每个人按时间顺序排列的动作。例如,对于 joe,这看起来像 at_home ->driving ->driving -> at_store -> at_store ->driving ->driving -> at_home
但是,我想删除任何重复的“驾驶”状态,只保留最早的。例如,对于 joe,这看起来像 at_home ->driving -> at_store -> at_store ->driving -> at_home。我不想删除重复的“at_home”或“at_store”
在本例中,我想从 12:15 开始保持“驾驶”状态,并在 16:00 保持“驾驶”状态,同时删除后面的重复状态。
我想专门为每个人执行此操作,因此当我执行“按 time_updated 排序”时,我可以按顺序查看该人的所有条目。
如果我使用"select * from db where name = 'joe' order by time_updated" 查询结果表,我的理想结果是:
| serial(pk) | name | status | location | time_updated |
|---|---|---|---|---|
| 1 | 'joe' | 'at_home' | 'USA' | 01:30 |
| 3 | 'joe' | 'driving' | 'USA' | 12:15 |
| 5 | 'joe' | 'at_store' | 'USA' | 15:00 |
| 5 | 'joe' | 'at_store' | 'USA' | 15:15 |
| 6 | 'joe' | 'driving' | 'USA' | 16:00 |
| 8 | 'joe' | 'at_home' | 'USA' | 20:00 |
有没有办法在 postgres 中做到这一点?
谢谢
【问题讨论】:
标签: sql postgresql