NULLIF在Amazon Redshift中产生错误的输出?

时间:2016-07-26 15:16:09

标签: sql postgresql amazon-redshift window-functions nullif

以下代码应为列laglag2生成相同的值:

CREATE TABLE bug1 (
  id INT,
  value INT
);

INSERT INTO bug1 VALUES (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3);

SELECT
  id,
  value,
         (LAG(value) OVER (PARTITION BY id ORDER BY value))     lag,
  NULLIF((LAG(value) OVER (PARTITION by id ORDER BY value)), 0) lag2
FROM bug1
ORDER BY id, value;

实际上,在PostgreSQL 9上运行它会产生预期的输出:

id  v  lag  lag2
1   1       
1   2   1   1
1   3   2   2
2   1       
2   2   1   1
2   3   2   2

但是,在Redshift上运行它会产生错误的结果:

id  v  lag  lag2
1   1       2
1   2   1   3
1   3   2   
2   1       2
2   2   1   3
2   3   2

这是预期的吗?我http://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#testing-ctx-management但没有回复。

1 个答案:

答案 0 :(得分:1)

这不是预期的;对我来说看起来像个bug。如果打算这样做,那么使用LEAD()代替并反转ORDER BY子句,我们期望与原始LAG()查询中的结果完全相同:

SELECT
  id,
  value,
         (LEAD(value) OVER (PARTITION BY id ORDER BY value desc))     lead,
  NULLIF((LEAD(value) OVER (PARTITION by id ORDER BY value desc)), 0) lead2
FROM bug1
ORDER BY id, value;

但这是我们得到的:

 id | value | lead | lead2
----+-------+------+-------
  1 |     1 |      |
  1 |     2 |    1 |     1
  1 |     3 |    2 |     2
  2 |     1 |      |
  2 |     2 |    1 |     1
  2 |     3 |    2 |     2