Oracle根据条件获取最新变更日期

rocky09

我有此下表tbl_subscriptions。

+-----------+--------+----------+--------+
| Sub.Date  |   ID   | POSITION | STATUS |
+-----------+--------+----------+--------+
| 8/22/2018 | 254515 | BROWN    | OPEN   |
| 8/21/2018 | 254515 | ORANGE   | CLOSE  |
| 8/20/2018 | 254515 | RED      | CLOSE  |
| 8/19/2018 | 254515 | ORANGE   | CLOSE  |
| 8/18/2018 | 254515 | BLUE     | CLOSE  |
| 8/17/2018 | 254515 | BLUE     | CLOSE  |
| 8/16/2018 | 254515 | BLUE     | CLOSE  |
| 8/15/2018 | 254515 | BLUE     | CLOSE  |
| 8/14/2018 | 254515 | ORANGE   | CLOSE  |
| 8/13/2018 | 254515 | BLUE     | CLOSE  |
+-----------+--------+----------+--------+

我真的很努力做到以下几点。我有成千上万个带有各种ID的条目。我需要获取所有“打开”条目以及最近从“蓝色”更改为“其他位置”的时间。参见下文,最近,头寸已于2018年8月19日从蓝色更改为橙​​色。所以,我想看这样的数据。

+-----------+--------+----------+--------+-----------------+
| Sub.Date  |   ID   | POSITION | STATUS | Pos. Changed on |
+-----------+--------+----------+--------+-----------------+
| 8/22/2018 | 254515 | BROWN    | OPEN   | 8/19/2018       |
+-----------+--------+----------+--------+-----------------+

我什至不知道如何实现这一目标。这至少在Oracle查询中是可能的。

戈登·利诺夫

您可以使用窗口功能来做到这一点:

select t.*
from (select t.*,
             max(case when position = 'ORANGE' and prev_position = 'BLUE' then sub_date end) over (partition by id) as change_date
      from (select t.*,
                   lag(position) over (partition by ID order by sub_date) as prev_position
            from t
           ) t
      ) t
where status = 'OPEN';

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章