以下代码应为列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
这是预期的吗?我http://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html#testing-ctx-management但没有回复。
答案 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