在Postgres中将字符串转换为bool_and中的boolean或integer

时间:2017-06-13 10:28:15

标签: postgresql

我有以下查询来检索具有state = 'error'的所有记录,直到状态不同based on this question

当前查询如下所示

SELECT * from (select id, subscription_id, state, created_at,
   bool_and(state='error') OVER (order by created_at, id) AS ok 
   FROM messages ORDER by created_at) m2 
   WHERE subscription_id = 1;

但是如您所见,所有州都被视为假,忽略了bool_and(state='error')条件。

   id    | subscription_id | state |         created_at         | ok 
---------+-----------------+-------+----------------------------+----
   69480 |               1 | error | 2015-06-30 15:20:03.041045 | f
   69482 |               1 | error | 2015-06-30 15:20:04.582907 | f
   69492 |               1 | sent  | 2015-06-30 22:50:04.50478  | f
   69494 |               1 | error | 2015-06-30 22:50:06.067279 | f
   69502 |               1 | error | 2015-07-01 22:50:02.356113 | f

我希望所有ok行在tstate = 'error'时返回f当州有其他内容时。

我读到bool_and只接受布尔值和整数,但鉴于条件的结果应该是布尔值,我不确定这个吗?

知道为什么这不起作用以及如何确保它有效?

2 个答案:

答案 0 :(得分:2)

您不会为bool_and分区聚合,因此会将其聚合在所有行上 - 因此您只有一个state=sent,这意味着bool_and(state='error') is false整体

尝试将partition by state添加到over(部分

<强>更新  更好的改变

bool_and(state='error') OVER (order by created_at, id) AS ok

bool_and(state='error') OVER (partition by state) AS ok

答案 1 :(得分:2)

尝试:

SELECT  *
FROM    (
        SELECT      id
                , subscription_id
                , state
                , created_at
                , bool_and(state = 'error')
                OVER (PARTITION BY state ORDER BY created_at, id) AS ok 
        FROM        messages
        ORDER BY    created_at
    ) AS m2
WHERE   subscription_id= 1;