sql - 根据整列的平均值过滤表格

标签 sql postgresql

我曾尝试根据列的平均值过滤表格,但不知何故它不起作用。它不返回任何东西。平均值约为 102,用它替换 AVG 子句确实会返回正确的行。

我怎样才能让它正常工作?

SELECT
ce.customer_id,
ce.first_name,
ce.total

FROM
(SELECT 
p.customer_id,
c.first_name,
SUM(p.amount) AS total

FROM payment as p
JOIN customer as c ON p.customer_id=c.customer_id
GROUP BY p.customer_id,c.first_name) AS ce

GROUP BY ce.customer_id,ce.first_name,ce.total

HAVING ce.total > AVG(ce.total)

最佳答案

您的查询有多个错误。外部 GROUP BY 没有意义。

我的建议是使用窗口函数。在这种情况下,您需要总数的平均值,因此如下所示:

SELECT ce.customer_id, ce.first_name, ce.total
FROM (SELECT p.customer_id, c.first_name, SUM(p.amount) AS total,
             AVG(SUM(p.amount)) OVER () as avg_total
      FROM payment p JOIN
           customer c
           ON p.customer_id = c.customer_id
      GROUP BY p.customer_id, c.first_name
     ) ce
WHERE ce.total > avg_total

关于sql - 根据整列的平均值过滤表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45466521/

相关文章:

sql - 多个多对多双向自内连接,无需重复整个查询

postgresql - PostGis 距离计算

postgresql - 无法从 postgres 获取结果

android - 在这种情况下如何使用 JOIN 和 CASE WHEN 语句(sqlite android)

mysql - 有什么方法可以使用 CASE 语句加快查询速度吗?

mysql - 使用 MySQL 创建循环排列的优雅方法

sql - Zope : standard_error_message: ZSQLMethod not working

postgresql - 如何将从函数返回的 bool 值分配给 PostgreSQL 9.4 中的变量?

sql - Postgres 交叉表和聚合在一起

ruby-on-rails - postgres/postgreSQL fatal error : database "ew_dev" does not exist