我有一张类似的表格:
+----+--------+--------+------------+-----------+
| id | amount | rif_id | date | is_closed |
+----+--------+--------+------------+-----------+
| 1 | 20 | NULL | 2017-11-12 | 1 |
| 2 | -5 | 1 | 2017-11-13 | NULL |
| 3 | -10 | 1 | 2017-11-24 | NULL |
| 4 | 7 | NULL | 2017-11-25 | 0 |
| 5 | -5 | 1 | 2017-11-26 | NULL |
| 6 | -5 | 4 | 2017-11-28 | NULL |
| 7 | 11.20 | NULL | 2017-11-30 | 0 |
+----+--------+--------+------------+-----------+
我需要获取更新近期ID的列表,其中sum的数量等于零,参考rif_id。
在我的例子中,我需要得到这个结果:
+----+--------+--------+------------+-----------+
| id | amount | rif_id | date | is_closed |
+----+--------+--------+------------+-----------+
| 5 | -5 | 1 | 2017-11-26 | NULL |
+----+--------+--------+------------+-----------+
我需要ID 5,因为该数量为1的金额为1和2的3正好为零。
仅供参考,专栏" is_closed"在表中插入最后一个事务时更新为1。实际上,当插入ID 5时,我的脚本使用" is_closed"计算并更新ID 1。 1.不知道SQL SELECT创建是否重要。
答案 0 :(得分:0)
我认为你可以这样做:
ref_id
且id <
当前记录sum(t2.amount) = 0
Order by id desc Limit 1
Select
t1.id,
t1.amount,
t1.rif_id,
t1.date,
t1.is_closed
From
table t1
left join table t2 on t2.ref_id = t1.ref_id and t2.id < t1.id
Group by
t1.id,
t1.amount,
t1.rif_id,
t1.date,
t1.is_closed
Having
sum(t2.amount) = 0
Order by
id desc
Limit 1