PostgreSQL:如何将两列相乘并在同一查询中显示结果?

Joh*_*ohn 4 sql postgresql

我有一个查询,它的select语句是这样的:

select Greatest(p.price,0) as newprice, sum(q.qty) as qty
from ....
Run Code Online (Sandbox Code Playgroud)

它给了我:

     newprice qty
      10      1
      0       1
      100     2
      1       2
Run Code Online (Sandbox Code Playgroud)

我想将newprice与qty相乘得到:

    newprice  qty   result
      10      1      10
      0       1      0
      100     2     200
      1       2      2
Run Code Online (Sandbox Code Playgroud)

当我尝试这样做select Greatest(p.price,0) as newprice, sum(q.qty) as qty, newprice * qty时说

ERROR: column "newprice" does not exist
Run Code Online (Sandbox Code Playgroud)

我真的不需要这个额外的专栏.

我真正想要的是:SUM(Greatest(p.price,0) * SUM(q.qty)) 它应该给出价值,212但它说ERROR: aggregate function calls cannot be nested

基本上我只需要将两列相乘并对结果求和.我知道我可以使用类似于此处所示的CTE ,但我想知道是否有更简单的方法来减少代码.

Jan*_* K. 7

你可以重复你写的内容:

select Greatest(p.price,0) as newprice,
       sum(q.qty) as qty,
       Greatest(p.price,0) * sum(q.qty) as result
from ...
Run Code Online (Sandbox Code Playgroud)

或者,您可以将select语句包装到临时派生表(PostgreSQL:在同一查询中使用计算列)

select tmp.newprice,
       tmp.qty,
       tmp.newprice * tmp.qty as result
from (
    select Greatest(p.price,0) as newprice,
           sum(q.qty) as qty
    from ...
) as tmp
Run Code Online (Sandbox Code Playgroud)