如何在这个mysql查询中创建RUNNING TOTAL

时间:2014-11-23 16:35:49

标签: mysql

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

此查询正常。有没有办法将运行总利润字段添加到此查询中,以执行已在查询中计算的利润的运行总和?

1 个答案:

答案 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;