SELECT
sum(unique1) OVER () AS total,
sum(unique1) OVER
(PARTITION BY four ORDER BY unique1 RANGE BETWEEN 5::int8 PRECEDING AND 6::int2 FOLLOWING),
unique1,
four
FROM
tenk1
WHERE
unique1 < 10;
返回:
total | sum | unique1 | four
-------+-----+---------+------
45 | 4 | 0 | 0
45 | 12 | 4 | 0
45 | 12 | 8 | 0
45 | 6 | 1 | 1
45 | 15 | 5 | 1
45 | 14 | 9 | 1
45 | 8 | 2 | 2
45 | 8 | 6 | 2
45 | 10 | 3 | 3
45 | 10 | 7 | 3
(10 rows)
基于 this 的细微更改
由于按四分区,每个框架只有 2 或 3 行。如果你在前面 5 个和后面 6 个之间,那么我认为在这种情况下,行/范围框架并不重要。我认为 range from、rows from 会返回相同的结果。因为 5 前 6 后每帧覆盖了足够的 2、3 行。
但是这确实很重要。我想我确实理解使用 ROWS
而不是 RANGE
的相同查询。
引自手册:
In RANGE or GROUPS mode, a frame_start of CURRENT ROW means the frame starts with the current row's first peer row (a row that the window's ORDER BY clause sorts as equivalent to the current row), while a frame_end of CURRENT ROW means the frame ends with the current row's last peer row. In ROWS mode, CURRENT ROW simply means the current row.
问题:如何解释
partition by four order by unique1 rows between 5::int8 preceding and 6::int2 following
最佳答案
- In
ROWS
mode, the offset must yield a non-null, non-negative integer, and the option means that the frame starts or ends the specified number of rows before or after the current row.[...]
- In
RANGE
mode, these options require that theORDER BY
clause specify exactly one column. The offset specifies the maximum difference between the value of that column in the current row and its value in preceding or following rows of the frame. The data type of the offset expression varies depending on the data type of the ordering column.
(重点是我的。)
所以ROWS
,您将获得当前行之前的 5 行和之后的 6 行。与RANGE
,您将得到 unique1
所在的行不比 unique1
少 5 block 或多 6 block 当前行。
在您的示例中,如果您考虑第一行,ROWS BETWEEN ... AND 6 FOLLOWING
将包括第三行,但是 RANGE BETWEEN ... AND 6 FOLLOWING
不会,因为 8(第三行 unique1
的值)和 0 之间的差大于 6。
关于sql - 使用 RANGE 模式理解窗函数框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73440298/