【发布时间】:2018-11-29 10:12:21
【问题描述】:
我试图通过编写一些示例查询来理解 postgres 中的 PARTITION BY。我有一个运行查询的测试表。
id integer | num integer
___________|_____________
1 | 4
2 | 4
3 | 5
4 | 6
当我运行以下查询时,我得到了预期的输出。
SELECT id, COUNT(id) OVER(PARTITION BY num) from test;
id | count
___________|_____________
1 | 2
2 | 2
3 | 1
4 | 1
但是,当我将 ORDER BY 添加到分区时,
SELECT id, COUNT(id) OVER(PARTITION BY num ORDER BY id) from test;
id | count
___________|_____________
1 | 1
2 | 2
3 | 1
4 | 1
我的理解是 COUNT 是针对属于分区的所有行计算的。在这里,我按 num 对行进行了分区。分区中的行数是相同的,有或没有 ORDER BY 子句。为什么输出会有差异?
【问题讨论】:
-
第二种情况,postgre统计
id小于等于实际id的行数 -
@RadimBača 是 postgres 特有的东西还是它应该如何工作?我不明白查询是如何按照您描述的方式解释的。
-
使用 COUNT(*) 代替 COUNT(id) 得到相同的结果。
-
见the documentation关于窗口函数,特别是:
By default, if ORDER BY is supplied then the frame consists of all rows from the start of the partition up through the current row, plus any following rows that are equal to the current row according to the ORDER BY clause. When ORDER BY is omitted the default frame consists of all rows in the partition. -
感谢您的信息。我现在明白发生了什么。我错过了文档中提供的信息。
标签: sql postgresql window-functions