PostgreSQL:如何将两列相乘并在同一查询中显示结果?
我有一个查询,它的select语句如下:PostgreSQL:如何将两列相乘并在同一查询中显示结果?,sql,postgresql,Sql,Postgresql,我有一个查询,它的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与数量相乘,得到: newprice qty result 10 1 10
select Greatest(p.price,0) as newprice, sum(q.qty) as qty
from ....
它给了我:
newprice qty
10 1
0 1
100 2
1 2
我想将newprice与数量相乘,得到:
newprice qty result
10 1 10
0 1 0
100 2 200
1 2 2
当我尝试执行时,选择最大(p.price,0)作为newprice,sum(q.qty)作为qty,newprice*qty
它会显示
ERROR: column "newprice" does not exist
我真的不需要这个额外的专栏
我真正想要的是:SUM(最大(p.price,0)*SUM(q.qty))
它应该给出值212
,但它说错误:聚合函数调用不能嵌套
基本上,我所需要的就是将两列相乘,然后对结果求和。
我知道我可以使用类似于图中所示的CTE,但我想知道是否有一种更简单的方法可以使用更少的代码。查询应该是这样的:
select *, newprice*qty from
(
select Greatest(p.price,0) as newprice, sum(q.qty) as qty
from ....
) T
或
更新:
您在查询中使用了groupby
(我假设是因为聚合),为了找到sum(newprice*qty),您需要一个子选择:
select sum(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 ...
或者,可以将select语句包装到临时派生表()
试试这个:
select sum(price*qty) as result
from yourtable;
我正在努力避免这个。。。因为我必须用另一个select来包装它以获得最终值(在我的示例212中)
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
select sum(price*qty) as result
from yourtable;