sql - PostgreSQL Where 计数条件

标签 sql postgresql group-by having

我在 PostgreSQL 中有以下查询:

SELECT 
    COUNT(a.log_id) AS overall_count
FROM 
    "Log" as a, 
    "License" as b 
WHERE 
    a.license_id=7 
AND 
    a.license_id=b.license_id 
AND
    b.limit_call > overall_count
GROUP BY 
    a.license_id;

为什么会出现此错误:

ERROR: column "overall_count" does not exist

我的表结构:

License(license_id, license_name, limit_call, create_date, expire_date)
Log(log_id, license_id, log, call_date)

我想检查许可证是否已达到特定月份的调用限制。

最佳答案

SELECT a.license_id, a.limit_call
     , count(b.license_id) AS overall_count
FROM   "License"  a
LEFT   JOIN "Log" b USING (license_id)
WHERE  a.license_id = 7 
GROUP  BY a.license_id  -- , a.limit_call  -- add in old versions
HAVING a.limit_call > count(b.license_id)

自 Postgres 9.1 以来,主键涵盖了 GROUP BY 中表的所有列。条款。在旧版本中,您必须添加 a.limit_call GROUP BY 列表。 release notes for 9.1 :

Allow non-GROUP BY columns in the query target list when the primary key is specified in the GROUP BY clause

进一步阅读:

您在 WHERE 中的情况子句必须移动到 HAVING 子句,因为它引用聚合函数的结果( WHERE 已应用)。并且您不能在 HAVING 中引用输出列(列别名)子句,您只能在其中引用输入列。所以你必须重复这个表达。 The manual:

An output column's name can be used to refer to the column's value in ORDER BY and GROUP BY clauses, but not in the WHERE or HAVING clauses; there you must write out the expression instead.

我颠倒了 FROM 中表格的顺序子句并稍微清理了语法以减少混淆。 <强> USING 在这里只是为了方便记号。

我用了 LEFT JOIN 而不是 JOIN ,因此您根本不会排除没有任何日志的许可证。

count() 只计算非空值.因为你想计算表 "Log" 中的相关条目使用 count(b.license_id) 更安全也更便宜。该列用于连接,因此我们不必担心该列是否可以为空。
count(*)甚至更短,更快,然而。如果你不介意得到 1 的计数对于 0左表中的行,使用它。

另外:我建议不要使用mixed case identifiers如果可能,在 Postgres 中。非常容易出错。

关于sql - PostgreSQL Where 计数条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8119489/

相关文章:

sql - 合并时如何避免从源表插入重复记录?

sql - 将空间用于千位分隔符报告服务

php - 没有数据的数据库的PostgreSql复制结构

sql - PostgreSQL 9.6 - 在冲突时插入并在返回时更新

r - 指定 dplyr 列名称

mysql - 如何从表中选择多个不同的数据?

postgresql - 显示 postgresql 数据库架构

python - 如何旋转数据框

sql - 在 Oracle 中选择分组集中的最新数据

SQL ON DELETE CASCADE 与删除业务逻辑