MariaDB [sandbox]> create table t(userid int,dt date, amount int);
Query OK, 0 rows affected (0.28 sec)
MariaDB [sandbox]> truncate table t;
Query OK, 0 rows affected (0.20 sec)
MariaDB [sandbox]> insert into t values
-> (123 , '2017-01-01' , 5) ,
-> (123 , '2017-01-03' , 2),
-> (124 , '2017-01-04' , 2) ,
-> (124 , '2017-01-04' , 3),
-> (123 , '2017-01-05' , -2),
-> (125 , '2017-01-01' , 5) ,
-> (125 , '2017-01-03' , 2),
-> (125 , '2017-01-05' , -6),
-> (126 , '2017-01-01' , 5) ,
-> (126 , '2017-01-02' , -10),
-> (126 , '2017-01-03' , 2),
-> (126 , '2017-01-05' , -10),
-> (126 , '2017-01-06' , 13);
Query OK, 13 rows affected (0.06 sec)
Records: 13 Duplicates: 0 Warnings: 0
MariaDB [sandbox]>
MariaDB [sandbox]>
MariaDB [sandbox]>
MariaDB [sandbox]> select s.userid,s.dt,s.amount,
-> case when s.crs is null then 0 else s.crs end crs,
-> case when s.exhaust is null then 0 else s.exhaust end exhaust,
-> case when s.amount > 0 and s.amount <= s.crs and s.crs > 0 then 'Fully paid'
-> when s.amount > 0 and s.amount > s.crs and s.crs > 0 then concat('Part paid -' ,s.crs)
-> else ''
-> end msg
-> from
-> (
-> select t1.*,
-> if(t1.userid <> @p ,
-> @crs:=(select sum(t2.amount) * - 1 from t t2 where t2.userid = t1.userid and t2.amount < 0)
-> ,@crs:[email protected]) crs,
-> if(t1.amount < 0 ,@crs:[email protected],if (t1.amount > @crs , @crs:=0,@crs:[email protected] - t1.amount)) exhaust,
-> @p:=t1.userid p
->
-> from (select @p:=0,@crs:=0) p ,t t1
-> order by t1.userid, t1.dt
->) s
-> ;
+--------+------------+--------+------+---------+--------------+
| userid | dt | amount | crs | exhaust | msg |
+--------+------------+--------+------+---------+--------------+
| 123 | 2017-01-01 | 5 | 2 | 0 | Part paid -2 |
| 123 | 2017-01-03 | 2 | 0 | 0 | |
| 123 | 2017-01-05 | -2 | 0 | 0 | |
| 124 | 2017-01-04 | 2 | 0 | 0 | |
| 124 | 2017-01-04 | 3 | 0 | 0 | |
| 125 | 2017-01-01 | 5 | 6 | 1 | Fully paid |
| 125 | 2017-01-03 | 2 | 1 | 0 | Part paid -1 |
| 125 | 2017-01-05 | -6 | 0 | 0 | |
| 126 | 2017-01-01 | 5 | 20 | 15 | Fully paid |
| 126 | 2017-01-02 | -10 | 15 | 15 | |
| 126 | 2017-01-03 | 2 | 15 | 13 | Fully paid |
| 126 | 2017-01-05 | -10 | 13 | 13 | |
| 126 | 2017-01-06 | 13 | 13 | 0 | Fully paid |
+--------+------------+--------+------+---------+--------------+
13 rows in set (0.03 sec)
注意してください: - 私は完全にこれをテストしていません!
@Salmon返信ありがとうございますが、何百万ものレコードで動作するとは思いませんか? –
排出日を追加することは可能ですか? –
あなたはどのようにn Part Paidsで構成された完全支払いを表示しますか?またはn Part Paidsで構成されたPart Paid? –