繁体   English   中英

Postgres SQL计算计算总数的平均值

[英]Postgres SQL calculate average of calculated totals

我正在尝试编写一个查询来返回所有高于平均美元销售额的产品。 相关的表格和列是:

  • 产品:prod_id:整数,价格:十进制
  • ORDERLINES:prod_id:整数,数量:整数

我可以编写每个产品获得美元销售额的子查询,但是我在将该平均函数应用于该子查询时遇到了麻烦。 我尝试的一切都会返回语法错误。 以下是我认为应该接近答案:

select avg(sum) as avg_sales 
from (
   select sum(b.quantity * a.price) as total_sales 
   from products a, orderlines b 
   where a.prod_id = b.prod_id 
   group by a.prod_id
);

当我尝试这个时,我得到:

错误:FROM中的子查询必须具有别名。

我不明白,但我是Postgres的新手。 无论如何,添加别名给了我:

select avg(totals) as avg_sales 
from (
    select sum(b.quantity * a.price) as total_sales 
    from products a, orderlines b 
    where a.prod_id = b.prod_id group by a.prod_id
) as totals;

当我尝试这个时,我得到:错误:函数avg(记录)不存在

我意识到上面的代码只是获得了整体平均销售额。 如果我能获得平均销售额,那么应该很容易获得高于平均水平的产品。

当我尝试这个时,我得到:错误:函数avg(记录)不存在

这是因为您将派生表的别名传递给avg()函数,这意味着您将完整的行(=记录)传递给它,而不是单个列(值)。

要使其正常工作,您需要使用:

select avg(totals.total_sales) as avg_sales 
from (
    select sum(ol.quantity * p.price) as total_sales 
    from products p 
      join orderlines ol on p.prod_id = ol.prod_id
    group by p.prod_id
) as totals;

请注意,我用现代显式JOIN运算符替换了古老的,过时的和脆弱的隐式连接。 如果你正在学习SQL,你应该习惯这种语法。


要获得高于平均销售额的产品,您需要同时计算:每种产品的销售额平均销售额。

这可以通过在聚合时使用窗口函数来实现:

select p.prod_id, 
       sum(ol.quantity * p.price) as total_sales, 
       avg(sum(ol.quantity * p.price)) over () as average_sales
from products p 
  join orderlines ol on p.prod_id = ol.prod_id
group by p.prod_id;

现在可以将其包装在派生表中,以过滤掉总销售额较低的表:

select *
from (
  select p.prod_id, 
         sum(ol.quantity * p.price) as total_sales, 
         avg(sum(ol.quantity * p.price)) over () as average_sales
  from products p 
    join orderlines ol on p.prod_id = ol.prod_id
  group by p.prod_id
) t
where total_sales >= average_sales;

SQLFiddle示例: http ://sqlfiddle.com/#!15/7f8ab/1

你可以尝试这样的事情。 首先使用子查询查找平均销售额,然后获得高于该销售额的所有产品

SELECT p.prod_id, o.quantity
    FROM products p INNER JOIN orderlines o
    ON p.prod_id = o.prod_id
    WHERE o.quantity  >  (      SELECT AVG(ol.quantity)
                                FROM products pr INNER JOIN orderlines ol
                                ON pr.prod_id = ol.prod_id
                        )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM