2014-11-23 64 views
1
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 

此查詢正常工作。有沒有辦法將運行總利潤字段添加到此查詢中,該查詢執行的查詢中已計算的運行總和爲利潤如何在此mysql查詢中創建RUNNING TOTAL

+0

您可以只添加在PHP中的值 – Strawberry 2014-11-23 16:50:41

+0

@Strawberry ..偏離軌道,但我的要求是要做到在SQL – 2014-11-23 17:02:54

+0

但爲什麼強加這樣的需求? – Strawberry 2014-11-23 17:15:10

回答

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;