2017-02-22 76 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抱歉,我会感激如果可以给如何会像 –