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

时间:2015-06-18 07:25:59

标签: sql postgresql

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

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,但我想知道是否有更简单的方法来减少代码。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

查询应该是这样的:

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

OR

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

答案 2 :(得分:0)

试试这个:

select sum(price*qty) as result
from yourtable;