0

以下代码应为列lag和生成相同的值lag2

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

这是预期的吗?我在 AWS 论坛上问过,但没有回复。

4

1 回答 1

1

这不是预期的;对我来说看起来像一个错误。如果它是有意的,那么使用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
于 2016-07-27T22:07:52.543 回答