mysql - 如何在此 mysql 查询中创建 RUNNING TOTAL

标签 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

这个查询工作正常。有没有一种方法可以将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/

相关文章:

php - 从日期中减去 8 天 + 秒

mysql 从结果中,如何选择 2 列中具有相同值的行

mysql - 将一个表中的 SUM 值与另一个表中的变量相乘

Python(Mysql 连接器)-如何刷新光标上的结果

mysql - java.sql.BatchUpdateException : transaction too large, 长度:300200

php - 从包含不同且不相关信息的多个表中获取 mysql 搜索结果

php - 如何在 magento 结帐时在运输方式中添加额外价格

mysql - 从服务器检索数据到本地返回 SQLSTATE[42000] : Syntax error or access violation: 1142 SELECT command denied to user

mysql - 哪些使用 PostGIS 可以完成而使用 MySQL 无法完成的事情?

php - 在用户未登录然后登录的情况下,将重复数据放入购物车很困难