需要通过使用旧记录值填充空值的详细信息来基于列的优先级来获取每个id的状态。
我有一个称为通知的表,其中包含诸如错误,警告,运行和停止等其他状态的字段。
这些状态填充了SQL中的数据,如下所示
+---+-------------------------+-------+-------+-------+-------+
| id | utctimestamp |Trip |Warning| start | Load|
+---+-------------------------+-------+-------+-------+-------+
| 0 | 2018-12-03 06:56:51.955 | | | true | true |
| 1 | 2018-12-03 03:41:31.664 | | | | |
| 0 | 2018-12-03 03:26:29.099 | | false | | |
| 1 | 2018-12-02 20:33:07.0 | | | false | false |
| 1 | 2018-12-02 20:23:21.092 | | true | false | false |
| 0 | 2018-12-02 18:06:45.003 | true | | | |
| 0 | 2018-12-02 13:51:03.575 | | false | false | false |
| 1 | 2018-12-02 13:50:24.614 | false | false | false | false |
| 0 | 2018-12-02 07:24:00.996 | | | true | true |
| 1 | 2018-12-02 04:08:41.36 | false | | | |
| 0 | 2018-12-02 03:53:40.193 | | false | | |
| 0 | 2018-12-01 18:32:24.271 | false | | | |
状态将根据跳闸>警告>开始>负载的优先级进行计算,并且如果值为空,则必须用旧记录值填充这些值。
从上表的详细信息中,我们需要基于id的状态0和1导出状态。
对于0,即使开始状态为true,我们也需要将其状态视为跳闸,因为最后一次跳闸发生的记录仍仅处于真状态。
与ID 1相同,以前的旧记录包含警告为true(而以前的记录包含行程状态为false),因此状态1为警告。
所需的输出是
+---+-------------------------+
| id | status |
+---+-------------------------+
| 0 | trip |
| 1 | warning |
为此,我正在努力寻找或构造SQL查询。任何建议都会有帮助
答案 0 :(得分:0)
您希望lag()
带有忽略空值:
select s.*,
coalesce(trip, lag(trip ignore nulls) over (partition by id order by utctimestamp)) as imputed_trip,
coalesce(Warning, lag(Warning ignore nulls) over (partition by id order by utctimestamp)) as imputed_Warning,
coalesce(start, lag(start ignore nulls) over (partition by id order by utctimestamp)) as imputed_start,
coalesce(Load, lag(Load ignore nulls) over (partition by id order by utctimestamp)) as imputed_Load
from statuses s;