2017-02-22 103 views
1

我有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向下滾動或轉到下一頁 請幫助

+2

'按帳戶牛逼順序,日期降序,x' – litelite

+0

在這種情況下,'balanacy'會變得亂七八糟,不正確 –

+0

基於非標準語法添加'mysql'標籤 –

回答

1

這是一個解決方案,由txn建立的txn平衡。我用unionall(不參加)構建初始表作爲你的榜樣好像你不想與這兩個amountinamountout行:

select * 
from (
select 
@cnt := If(@prev=account , @cnt+1,1) rown, a.*, 
@balance := if( @prev=account, @balance + amountin - amountout, amountin - amountout) balance,               
@prev := account prev from 
(select account, date, amountin, 0 amountout from amountin 
union all 
select account, date, 0, amountout from amountout) a, (select @cnt := 1) b, (select @prev :='') c, (select @balance :=0) bal 
order by account, date 
    ) r 
    order by account, rown desc, date desc 

Here is a working exmaple with your data

+0

這是完美而美麗的,非常感謝,如果表格是3,我們添加另一個表'thirdTable'表示'balance = lastbalance + amountin + thirdamount-amountout'第三個表與其他表具有相同的結構 –

+0

再次感謝你,對於遲到的+1抱歉,我會感激如果可以給如何會像 –