has_been window function?

问题描述 投票:0回答:2

this以下架构

CREATE TABLE test (
  id INT
  , is_true BOOL
);
INSERT INTO test (id,is_true) VALUES (1,FALSE);
INSERT INTO test (id,is_true) VALUES (2,FALSE);
INSERT INTO test (id,is_true) VALUES (3,TRUE);
INSERT INTO test (id,is_true) VALUES (4,FALSE); 

我提出这个问题:

SELECT 
    is_true
FROM test; 

当然给

FALSE
FALSE
TRUE
FALSE

我想要的是某种窗户?执行 HAS_BEEN_TRUE 而不是 IS_TRUE 并且尊重 id 排序的函数。这就是为什么我认为它可能是一个窗口函数——因为它必须对所有这样的行进行计算。

它应该回来

FALSE -- never been TRUE
FALSE -- never been TRUE
FALSE -- even though it IS TRUE, it has never been so previously
TRUE  -- now it HAS BEEN true. 

我也接受

FALSE
FALSE
TRUE
TRUE 

我想将其更改为 HAS_BEEN_OR_IS_TRUE。我真的很想在 redshift 中实现这一点,但我很高兴听到任何使用窗口函数执行此操作的数据库。

sql amazon-redshift window-functions
2个回答
0
投票

布尔列的窗口

max()
应该做你想做的事:

select t.*,
    max(is_true) over(
        order by id
        rows unbounded preceding
    ) has_been_or_is_true
from test t

或者,如果你只想查看前一行,忽略当前行,我们可以优化

row
框架:

select t.*,
    max(is_true) over(
        order by id
        rows between unbounded preceding and 1 preceding
    ) has_been_true
from test

0
投票

可以使用子查询,自己查:

SELECT 
    id,
    case when exists (select 1 from test t2 where t2.id<t.id and t2.is_true = TRUE) then TRUE else FALSE end wind
FROM test t
© www.soinside.com 2019 - 2024. All rights reserved.