如何计算postgresql中的布尔更改

s3fp2yjn  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(244)

我的table看起来像这样

目标是计算特定执行器的执行器状态在一段时间内(从列“执行器名称”中)更改的次数。请记住,一个特定的执行器有不同的执行器(例如heater has heator0、heator1等),目标是计算heater0+heater1+heator2+heater3(表的名称也是state
我试过这个:

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(例如,加热器0更换了3次,加热器1更换了2次,其他加热器(加热器0更换)

zed5wv10

zed5wv101#

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

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 子查询的子句。
请注意,此查询不会将时段中的第一个值计算为更改。只考虑进一步的变化。

vuv7lop3

vuv7lop32#

你可以用 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 条款。
请注意,这将第一次出现视为“更改”。不清楚这是否符合你的意图。

相关问题