gpt4 book ai didi

mysql - SQL 平衡计算按日期排序

转载 作者:行者123 更新时间:2023-11-28 23:19:35 26 4
gpt4 key购买 nike

我有 2 个表 AmountIn 和 AmountOut。

第一个表 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 |
+--------+----+---------+-----------+

第二个看起来像:

出金额

+--------+--------------+-----------+
| 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 |
+--------+----+---------+-----------+

现在我想要一个显示结果如下的查询:对于帐户 A

+--------+--------------+----------+-----------+------------+
| 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

但它给我的结果是按日期升序排列的,我希望它按日期降序排列。我不需要在顶部看到最后的操作,否则当数据不足时,我将很难向下滚动或转到下一页请帮忙

最佳答案

这是一个通过 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

关于mysql - SQL 平衡计算按日期排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42396639/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com