【问题标题】:SQL Select to identify device status based on the multiple status fields valuesSQL Select 根据多个状态字段值识别设备状态
【发布时间】:2018-12-03 12:08:27
【问题描述】:

需要根据列的优先级通过旧记录值填充空值的详细信息来获取每个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 |       |       |       |

status 将按照trip > warning> start > load 的优先级进行计算,如果为null,则必须使用旧记录值填充值。

从上表的详细信息中,我们需要根据它们的状态推导出 id 的 0 和 1 的状态。

对于 0,即使开始状态为真,我们也需要将其状态视为行程,因为上次行程发生记录仍处于真状态。

与 Id 1 的相同方式,之前的旧记录包含警告为 true(之前的记录包含行程状态为 false),因此 1 的状态为警告。

想要的输出是

+---+-------------------------+
| id | status                 |
+---+-------------------------+
| 0 | trip                    |
| 1 | warning                 |

为此,我正在努力寻找或构建 SQL 中的查询。任何建议都会有所帮助

【问题讨论】:

  • 我删除了不兼容的数据库标签。请标记您真正使用的数据库。
  • 嗨 Gordan,我正在使用亚马逊红移,甚至我在 Postgres 中尝试过这个示例

标签: sql amazon-redshift aggregate-functions coalesce


【解决方案1】:

你想要 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;

【讨论】:

  • 感谢 Gordan,通过上面的 SQL 查询,我可以用以前的现有值填充空值。但是如何通过考虑上面的查询,根据列的优先级(trip > warning > start > load)找到id的最终状态。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-09
  • 1970-01-01
  • 2017-07-18
  • 2013-12-16
  • 2021-03-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多