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

问题描述 投票:3回答:3

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

select Greatest(p.price,0) as newprice, sum(q.qty) as qty
from ....

它给了我:

     newprice qty
      10      1
      0       1
      100     2
      1       2

我想将newprice与qty相乘得到:

    newprice  qty   result
      10      1      10
      0       1      0
      100     2     200
      1       2      2

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

ERROR: column "newprice" does not exist

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

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

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

sql postgresql
3个回答
6
投票

你可以重复你写的内容:

select Greatest(p.price,0) as newprice,
       sum(q.qty) as qty,
       Greatest(p.price,0) * sum(q.qty) as result
from ...

或者,您可以将select语句包装到临时派生表(PostgreSQL: using a calculated column in the same query

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

3
投票

查询应该是这样的:

select *, newprice*qty from
(
    select Greatest(p.price,0) as newprice, sum(q.qty) as qty
    from ....
) T

要么

select Greatest(p.price,0) as newprice, sum(q.qty) as qty, Greatest(p.price,0)*sum(q.qty) as result
from ....

更新:

你在查询中使用group by(我推测是因为聚合)并且为了找到sum(newprice * qty),你需要一个子选择:

select sum(newprice*qty) from
(
    select Greatest(p.price,0) as newprice, sum(q.qty) as qty
    from ....
) T

0
投票

试试这个:

select sum(price*qty) as result
from yourtable;
© www.soinside.com 2019 - 2024. All rights reserved.