我有2個表AmountIn和AmountOut。SQL平穩度計算排序日期
第一個表Amountin樣子:
AmountIn
+--------+--------------+-----------+
| account| date | AmountIn |
+--------+--------------+-----------+
| A | 2017/2/6 | 200 |
| A | 2017/2/5 | 100 |
| A | 2017/2/5 | 500 |
| B | 2017/2/1 | 1000 |
| B | 2017/2/1 | 2000 |
| C | 2017/1/20 | 25 |
+--------+----+---------+-----------+
,第二個看起來像:
AmountOut
+--------+--------------+-----------+
| account| date |AmountOut |
+--------+--------------+-----------+
| A | 2017/2/8 | 200 |
| A | 2017/2/7 | 100 |
| A | 2017/2/6 | 500 |
| B | 2017/2/2 | 1000 |
| B | 2017/2/1 | 2000 |
| C | 2017/1/20 | 25 |
+--------+----+---------+-----------+
現在我想一個查詢,顯示結果如下: ForAccountA
+--------+--------------+----------+-----------+------------+
| account| date | AmountIn | AmountOut | Balancy |
+--------+--------------+-------- -+-----------+------------+
| A | 2017/2/8 | 0 | 200 | 0 |
| A | 2017/2/7 | 0 | 100 | 200 |
| A | 2017/2/6 | 200 | 0 | 300 |
| A | 2017/2/6 | 0 | 500 | 100 |
| A | 2017/2/5 | 100 | 0 | 600 |
| A | 2017/2/5 | 500 | 0 | 500 |
+--------+----+---------+----------+-----------+------------+
這意味着工會表和計算balancy
爲:
last balance + AmountIn - AmounOut
我的代碼是:
select
t.*,
@sum := if(@account = account,
@sum + AmountIn - AmountOut,
if((@account := account) is not null,
AmountIn - AmountOut, 0)
) balance
from (
select
*
from (
select
1 x,
account,
date,
AmountIn,
0 AmountOut
from AmountIn
union all
select
0 x,
account,
date,
0 AmountIn,
AmountOut
from AmountOut
) t order by account, date, x
) t cross join (select @account := null, @sum := 0) t2
但它給我造成的時間升序我希望它被訂購按日期遞減。我neet o看到上面的最後操作,否則當數據得到一個我將很難o向下滾動或轉到下一頁 請幫助
'按帳戶牛逼順序,日期降序,x' – litelite
在這種情況下,'balanacy'會變得亂七八糟,不正確 –
基於非標準語法添加'mysql'標籤 –