2012-02-21 77 views
0

我有一张表,我保存有关财务回报的信息。这些专栏包括收据,维修,service_amount,轮胎,燃料,薪金许可等。如何获取累计总计mysql

我想获得的累计净回笼,如:

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 
+1

你的问题是模糊的,它不详细,他们是如何计算的,将承担所有费用被算作“修理”并且是成本,而收据是信用? – 2012-02-21 09:15:19

回答

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 

子查询会计算您的成本和积分,然后外部查询执行您的运行总计。如果您需要在内连接中添加单独的列数,那么可以轻松添加它们。

+0

上述查询工作正常,但我不得不做一些更改,以获得下面所需的结果是从你张贴的修改后的查询。感谢西蒙,阿里伊萨和莫斯塔乔你们给我一个见解 – smilezjim 2012-02-21 10:54:38

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

将计数加在一起的地方在哪里?我认为OP想要加总数并计算合计 – Kaii 2012-02-21 09:27:46

+0

@Ali Issa总成本通过将service_amount,repairs,tires,salaries_allowances,clearing_fee等相加(总和)来计算,而净回报以收益计算 - 总和总成本但净支付是累积的。 – smilezjim 2012-02-21 09:29:22

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