2014-01-12 15 views
0

我从一个MySQL表中读取一些事务性的数据是这样的:如何返回相继排差异与其他数据(MySQL的)一列

SELECT bill_no as Document_No, bill_date as Trans_Date, bill_amount as Amount, 0 as Balance 
FROM bill_table 
WHERE consumer_name = 'John' 
UNION 
SELECT receipt_no as Document_No, receipt_date as Trans_Date, -receipt_amount as Amount, 0 as Balance 
FROM receipt_table 
WHERE consumer_name = 'John' 
ORDER BY Trans_Date 

导致这样的事情

 
+-----------+----------+------+-------+ 
|Document_No|Order_date|Amount|Balance| 
+-----------+----------+------+-------+ 
|BILL58788 |2010-08-09|493 | 0  | 
|BILL58789 |2010-08-10|789 | 0  | 
|REC_12379 |2010-08-11|-1282 | 0  | 
|BILL58788 |2010-08-12|1493 | 0  | 
|BILL58788 |2010-09-01|4930 | 0  | 
|REC_12380 |2010-10-02|-2000 | 0  | 
+-----------+----------+------+-------+ 

这给我所有的账单&约翰的收据细节。所有金额在同一栏中,帐单金额为正数&收据金额为负数。

在最后一列“平衡”,我希望有一个总的连续大量像这样的,动态计算:

 
+-----------+----------+------+-------+ 
|Document_No|Order_date|Amount|Balance| 
+-----------+----------+------+-------+ 
|BILL58788 |2010-08-09|493 | 493 | 
|BILL58789 |2010-08-10|789 | 1282 | 
|REC_12379 |2010-08-11|-1282 | 0  | 
|BILL58788 |2010-08-12|1493 | 1493 | 
|BILL58788 |2010-09-01|4930 | 6423 | 
|REC_12380 |2010-10-02|-2000 | 4423 | 
+-----------+----------+------+-------+ 

我知道我可以在PHP中获取数据后,做到这一点,但我想这样做mySQL本身。

可能吗?请帮忙。 在此先感谢。

回答

2

在MySQL中,要做到这一点最简单的方法是使用变量:

select Document_No, bill_date, bill_amount, 
     (@balance := @balance + bill_amount) as balance 
from ((SELECT bill_no as Document_No, bill_date as Trans_Date, bill_amount as Amount 
     FROM bill_table 
     WHERE consumer_name = 'John' 
    ) 
     UNION ALL 
     (SELECT receipt_no as Document_No, receipt_date as Trans_Date, -receipt_amount as Amount 
     FROM receipt_table 
     WHERE consumer_name = 'John' 
    ) 
    ) t cross join 
    (select @balance := 0) const 
ORDER BY Trans_Date; 
+0

那精美的作品。谢谢。我不熟悉在mySQL中使用变量。你能告诉我的目的: (select @balance:= 0)const – Xaq

相关问题