select saleid, orderno, orderdate,
sum(purchaseprice+purchaseshipping+paypalfee+storefee) as totalcost,
customerpaid as totalrevenue,
(customerpaid - sum(purchaseprice+purchaseshipping+paypalfee+storefee)) as profit,
ROUND((((customerpaid - sum(purchaseprice+purchaseshipping+paypalfee+storefee)) / customerpaid) * 100.00),2) as profitmargin
from tblsales
group by orderno having " . $having . "
order by $sort $order limit $offset,$rows
这个查询工作正常。有没有一种方法可以将running total profit 字段添加到此查询,以执行已在查询中计算的profit 的运行总和?
最佳答案
只需将其放入子查询并使用变量即可:
select t.*,
(@cumesum := @cumesum + profit) as runningprofit
from (select saleid, orderno, orderdate,
sum(purchaseprice+purchaseshipping+paypalfee+storefee) as totalcost,
customerpaid as totalrevenue,
(customerpaid - sum(purchaseprice+purchaseshipping+paypalfee+storefee)) as profit,
ROUND((((customerpaid - sum(purchaseprice+purchaseshipping+paypalfee+storefee)) / customerpaid) * 100.00),2) as profitmargin
from tblsales
group by orderno
having " . $having . "
) t cross join
(select @cumesum := 0) vars
order by $sort $order
limit $offset, $rows;
关于mysql - 如何在此 mysql 查询中创建 RUNNING TOTAL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27091375/