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
此查询正常。有没有办法将运行总利润字段添加到此查询中,以执行已在查询中计算的利润的运行总和?
答案 0 :(得分:2)
只需将其放在子查询中并使用变量:
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;