如何在MySQL中从同一个表中减去两个计算字段?

qf9go6mv  于 2023-02-07  发布在  Mysql
关注(0)|答案(2)|浏览(164)
SELECT   *, 
         SUM(price+shipping+paypalfee+storefee) AS totalcost, 
         customerpaid                           AS totalrevenue, 
         (totalcost - totalrevenue)             AS profit 
FROM     tblsales 
GROUP BY orderno 
HAVING   " . $having . " 
ORDER BY $sort $order 
LIMIT    $offset,$rows

如果省略(totalcost - totalrevenue) as profit,查询就可以正常工作。如何在同一个查询中使用totalcost和totalrevenue计算PROFIT?

np8igboo

np8igboo1#

你的问题的答案是,你必须重复这些表达式:

select *, sum(price+shipping+paypalfee+storefee) as totalcost
       customerpaid as totalrevenue,
       (sum(price+shipping+paypalfee+storefee) - customerpaid) as profit
from tblsales
group by orderno
having " . $having . "
order by $sort $order
limit $offset, $rows;

不允许在定义列别名的同一个select中使用列别名。
而且,您的查询看起来很奇怪。任何包含select *group by的查询都是可疑的。您有许多列(可能),其值将来自每个组的不确定行。一般情况下,您应该显式列出这些列,但对于group by,您尤其应该这样做。

zkure5ic

zkure5ic2#

你可以这样做SELECT *,(总成本-总收入)作为利润FROM(SELECT *,SUM(价格+运费+支付手续费+存储费)作为总成本,客户支付作为总收入,
FROM表销售分组依据订单no HAVING“. $having .“订单依据$排序$订单)LIMIT $偏移量,$行

相关问题