我收到了一張名爲「Stock」的表,如下所示。MySQL未結餘額貸方餘額餘額
+-----------+--------------+---------------+---------+
| client_id | date | credit | debit|
+-----------+--------------+---------------+---------+
| 1 | 01-01-2015 | 50 | 0 |
| 2 | 01-01-2015 | 250 | 0 |
| 2 | 01-01-2015 | 500 | 0 |
| 2 | 02-01-2015 | 0 | 500 |
| 1 | 02-01-2015 | 0 | 40 |
| 1 | 02-01-2015 | 0 | 80 |
| 3 | 05-01-2015 | 3000 | 0 |
| 2 | 06-01-2015 | 0 | 350 |
| 4 | 06-01-2015 | 0 | 1000 |
| 4 | 06-01-2015 | 0 | 2000 |
| 4 | 07-01-2015 | 500 | 0 |
| 5 | 07-01-2015 | 500 | 0 |
| 5 | 08-01-2015 | 500 | 0 |
| 1 | 09-01-2015 | 0 | 100 |
+-----------+--------------+---------------+---------+
我期待的結果是這樣的:
+---------+-----------+-------------+--------+---------+----------+
|client_id| date |Open_Balance | credit | debit | balance |
+---------+-----------+-------------+--------+---------+----------+
| 1 |01-01-2015 | 0 | 50 | 0 | 50 |
| 1 |02-01-2015 | 50 | 0 | 40 | 10 |
| 1 |02-01-2015 | 10 | 0 | 80 | -70 |
| 1 |09-01-2015 | -70 | 0 | 100 | -170 |
| 2 |01-01-2015 | 0 | 250 | 0 | 250 |
| 2 |01-01-2015 | 250 | 500 | 0 | 750 |
| 2 |02-01-2015 | 750 | 0 | 500 | 250 |
| 2 |06-01-2015 | 250 | 0 | 350 | -100 |
| 3 |05-01-2015 | 0 | 3000 | 0 | 3000 |
| 4 |06-01-2015 | 0 | 0 | 1000 | -1000 |
| 4 |06-01-2015 | -1000 | 0 | 2000 | -3000 |
| 4 |07-01-2015 | -3000 | 500 | 0 | -2500 |
| 5 |07-01-2015 | 0 | 500 | 0 | 500 |
| 5 |08-01-2015 | 500 | 500 | 0 | 1000 |
+---------+-----------+-------------+--------+---------+---- -----+
我需要平衡和「打開餘額」,由CLIENT_ID和日期順序來計算,如上圖所示。請幫忙。
先試試 – 2015-03-03 09:26:41
你是怎麼計算'Open balances''? – Saif 2015-03-03 09:37:36
每個client_id的初始'未結餘額'爲零。 – 2015-03-03 09:44:36