【发布时间】:2019-06-05 20:14:23
【问题描述】:
试图了解我该怎么做:
|id| timestamp | type |
|--|--------------------------|---------|
|11|2018-10-02 15:57:07.000000| open |
|11|2018-10-02 16:48:51.000000| closed |
|11|2018-10-05 08:59:27.000000| open |
|11|2018-10-05 09:59:18.000000| closed |
那个:
|id| open_ts | closed_ts |
|--|--------------------------|--------------------------|
|11|2018-10-02 15:57:07.000000|2018-10-02 16:48:51.000000|
|11|2018-10-05 08:59:27.000000|2018-10-05 09:59:18.000000|
我根据类型的条件进行了“自联接”。 这里有一个规则:在“打开”之后应该总是“关闭”。在“关闭”之前,它不能“打开”。 我最好的结果是:
|id| open_ts | closed_ts |
|--|--------------------------|--------------------------|
|11|2018-10-02 15:57:07.000000|2018-10-02 16:48:51.000000|
|11|2018-10-02 15:57:07.000000|2018-10-05 09:59:18.000000|
|11|2018-10-05 08:59:27.000000|2018-10-02 16:48:51.000000|
|11|2018-10-05 08:59:27.000000|2018-10-05 09:59:18.000000|
select z.id id, z.timestamp open_ts, o.timestamp closed_ts
from temp_event z
join temp_event o
on z.id=o.id
where z.type='open' and o.type='closed'
另外,我尝试在 (id)* 上使用 distinct,但我得到了错误的间隔值:
|id| open_ts | closed_ts |
|--|--------------------------|--------------------------|
|11|2018-10-02 15:57:07.000000|2018-10-02 16:48:51.000000|
|11|2018-10-05 08:59:27.000000|2018-10-02 16:48:51.000000|
* 来自附加表。此 id 存在于两个副本中,用于呈现表中的一个 id。
【问题讨论】:
标签: sql postgresql join timestamp