因此,今天早上我不小心在我的 CTE 中引用了一个不存在的“计数”列,我遇到了一个我认为是奇怪的错误。 Postgres 一直在寻找 GROUP BY 子句,尽管我不认为我在做聚合。再多玩一会儿,就会发现 table.count 相当于一个计数星函数。请考虑以下事项:
SELECT
c.clinic_id,
c.count,
count(*) as count_star
FROM clinic_member c
GROUP BY
c.clinic_id
ORDER BY clinic_id;
这将在我的数据集中生成如下所示的结果:
为了了解实际的 Postgres 语法规则是什么,我尝试在文档中搜索对此语法的引用,但找不到任何内容;只有很多关于 count(*) 的文档。谁能解释这是否是有效的 SQL 以及是否还有其他可以类似调用的聚合函数? Postgres 文档的链接如果存在的话会很棒。
注意。这是在 Postgres 9.5.9 上
最佳答案
这是有效的 Postgres 语法,因为在 Postgres 中,可以通过两种不同的方式调用具有与表类型匹配的单个参数的函数:
假设一个表名 foo
和一个名为 some_function
的函数,带有一个 foo
类型的参数,然后如下:
select some_function(f)
from foo f;
相当于
select f.some_function
from foo f;
别名实际上不是必需的:
select foo.some_function
from foo;
这是 Postgres 的“面向对象”结构的结果。
count()
可以采用任何参数 - 因此包括行引用 (=record)
select count(f)
from foo f;
相当于
select f.count
from foo f;
这记录在关于 Function Calls 的章节中在手册中:
A function that takes a single argument of composite type can optionally be called using field-selection syntax, and conversely field selection can be written in functional style. That is, the notations col(table) and table.col are interchangeable. This behavior is not SQL-standard but is provided in PostgreSQL because it allows use of functions to emulate “computed fields”. For more information see Section 8.16.5.
关于sql - 计数聚合点计数语法 (.count),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47229778/