加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

PostgreSQL其中计数条件

发布时间:2020-12-13 16:42:34 所属栏目:百科 来源:网络整理
导读:我在PostgreSQL中有以下查询: SELECT COUNT(a.log_id) AS overall_countFROM "Log" as a,"License" as b WHERE a.license_id=7 AND a.license_id=b.license_id AND b.limit_call overall_countGROUP BY a.license_id; 为什么我得到这个错误: ERROR: column
我在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)

要点

>在PostgreSQL 9.1之前的版本中,您必须向GROUP BY子句添加limit_call。
从版本9.1开始,在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

>我颠倒了你的表在查询中出现的顺序,并清理了一些语法,使它不那么混乱。使用在这里只是一个标志性的方便。
>我使用LEFT JOIN而不是JOIN,所以你不排除没有任何日志的许可证。
>您的WHERE条件必须移动到HAVING子句,因为您引用聚合函数的结果。而您不能在HAVING子句中引用输出列(列别名),您只能引用输入列。所以你必须重复表达。 Per documentation:

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.

>如果可能,我建议不要在Postgres中使用mixed case identifiers。很容易出错> count()只计算非空值。因为你想计数相关条目int表“日志”,使用count(b.license_id)更安全,更便宜一点。该列在连接中使用,因此我们不必打扰列是否为空。count(*)会更短,稍快一点。如果在左侧表格中为0行计数为1,则我将使用它。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读