如何获取累积总数mysql

时间:2012-02-21 09:05:19

标签: mysql

我有一张表,其中保存有关财务回报的信息。列包括收据,维修,service_amount,轮胎,燃料,salaries_allowances等。

我想获得累计净回报,如:

Date        Receipts       repairs      service amount  Total costs  net Return
2012-01-10  0.00           120,000.00   0.00            120,000.00   120,000.00
2012-01-12  60,000.00      0.00         0.00            60,000.00    60,000.00

我目前正在使用此查询:

SELECT 
        a.consignment_date, a.receipts, a.service_amount, a.repairs, a.tyres, 
        a.salaries_allowances, a.clearing_fee, a.others, 
        a.service_amount + a.repairs + a.tyres + a.salaries_allowances + a.clearing_fee + a.others as total_costs,
        (b.receipts -(a.service_amount + a.repairs + a.tyres + a.salaries_allowances + a.clearing_fee + a.others)) as netreturn 
FROM 
      vw_local_freight a CROSS JOIN vw_local_freight b 
WHERE 
      a.consignment_date >= b.consignment_date AND a.vehicle_no='123X' 
GROUP BY a.consignment_date

3 个答案:

答案 0 :(得分:0)

试试这个:

SET @runtot:=0;
SELECT
   q1.d,
   q1.c,
   (@runtot := @runtot + q1.c) AS rt
FROM
   (SELECT
       DAYOFYEAR(date) AS d,
       COUNT(*) AS c
    FROM  orders
    WHERE  hasPaid > 0
    GROUP  BY d
    ORDER  BY d) AS q1

答案 1 :(得分:0)

我会查看像

这样的查询
SELECT 
    consignment_date.*,
    consignment_date.credits - consignment_date.costs AS totalCosts,
    (@runningTotal := @runningTotal + consignment_date.credits - consignment_date.costs) AS netReturn
FROM (
    SELECT
        consignment_date,
        SUM(receipts) AS credits
        SUM(service_amount + repairs + tyres + salaries_allowances + clearing_fee + others) AS costs
    FROM vw_local_freight 
    WHERE vehicle_no = '123x'
    GROUP BY consignment_date
) AS a, (SELECT @runningTotal := 0) AS b

子查询计算您的成本和信用,然后外部查询执行您的运行总计。如果您需要在内部联接中使用单个列总和,那么可以很容易地添加它们。

答案 2 :(得分:0)

好的,我的答案基于您的查询,而不是您预期的表格结果:

SELECT *, receipts - total_costs as NetReturn FROM (
  SELECT a.consignment_date, sum(a.receipts) receipts, sum(a.service_amount),
    sum(a.repairs), sum(a.tyres), sum(a.salaries_allowances),
    sum(a.clearing_fee), sum(a.others), sum(a.service_amount + a.repairs
    + a.tyres + a.salaries_allowances + a.clearing_fee + a.others) as total_costs
  FROM  vw_local_freight a
  WHERE a.vehicle_no = '123X' 
  GROUP BY a.consignment_date
) S