【问题标题】:How to count Boolean changes in PostgreSQL如何计算 PostgreSQL 中的布尔变化
【发布时间】:2020-09-09 22:17:15
【问题描述】:

我的桌子是这样的

目标是计算特定执行器的 actuator_state(来自 actuator_names 列)在一段时间内更改了多少次。请记住,特定的执行器具有各种执行器(例如 Heater 有 Heator0、Heator1 等),目标是计算 Heater0+ Heater1+ Heator2+ Heater3 更改了多少次......(表的名称也是 state_actuator

我试过了:

SELECT actuator_nome AS NOME, 
SUM (DISTINCT CASE WHEN  actuator_state.actuator AND DISTINCT actuator_state.actuator_time AND DISTINCT actuator_state.actuator_state THEN 1 ELSE 0) AS TROCAS_ESTADO
FROM actuator_state WHERE actuator_time BETWEEN '2020-05-17 16:58:54' AND '2020-05-17 17:09:58' AND actuator_name='Heater'  

结果应该是 加热器:5个; (例如 Heater0 改变了 3 次,Heater1 改变了两次,其他 Heater 0 改变了)

【问题讨论】:

  • 请在所有大写字母上放轻松,尤其是在标题中。它被认为是大喊大叫。其次,仅使用您实际使用的数据库进行标记。你在 MySQL 和 SQLite 上也遇到了这个问题,没有明显的原因。
  • 请以文本的形式提供数据,切勿以图像的形式提供。声明您的 Postgres 版本和实际(最小)表定义(CREATE TABLE 语句)

标签: sql postgresql group-by window-functions gaps-and-islands


【解决方案1】:

您可以为此使用窗口函数:

select 
    actuator_name,
    count(*) filter(where actuator_state <> lag_actuator_state) no_changes
from (
    select 
        t.*,
        lag(actuator_state) 
            over(partition by actuator_name, actuator order by actuator_time) lag_actuator_state
    from mytable t
    where actuator_time between '2020-05-17 16:58:54' and '2020-05-17 17:09:58'
) t
group by actuator_name

子查询使用lag() 检索每个执行器的“先前”状态。然后,外部查询按actuator_name 聚合,并在每次连续值不相等时执行计数增加1

您可以根据需要在子查询的where 子句中添加额外的过滤器。

请注意,此查询不会将周期中的第一个值计为更改。仅考虑进一步的更改。

【讨论】:

    【解决方案2】:

    你可以使用lag():

    select actuator_name,
           count(*) filter (where prev_as is distinct from actuator_state)
    from (select sa.*,
                 lag(actuator_state) over (partition by actuator order by actuator_time) as prev_as
          from state_actuator sa
         ) sa
    where actuator_time between '2020-05-17 16:58:54' and '2020-05-17 17:09:58'    
    group by actuator_name;
    

    您也可以在 where 子句中过滤特定名称。

    请注意,这会将第一次出现视为“更改”。目前尚不清楚这是否符合您的意图。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-29
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 2017-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多