没有简单的方法。您需要使用自联接。
select t.*,
(coalesce(t_1.count, 0) - coalesce(t_2.count, 0)) * 100.0
from t left outer join
t t_1
on t.id = t_1.id + 1 left outer join
t t_2
on t.id = t_2.id + 2
确保所有原始left outer join
行都保留,即使没有前面的 id。
这是有效的,因为 id 是连续的。如果 id 不是连续的,并且计数单调增加,您可以使用相关子查询执行此操作:
select t.*,
(coalesce((select max(`count`) as val
from table1 t_1
where t_1.`count` < t.`count`
), 0)
) -
(coalesce((select max(`count`)
from table1 t_2
where t_2.`count` < (select max(`count`) from table1 t_1 where t_1.`count` < t.`count`)
), 0)
)
from table1 t
注意:如果两个值连续相同,这将无法正常工作。为此,您需要使用 id 代替:
select t.*,
(coalesce((select max(`count`) as val
from table1 t_1
where t_1.`id` < t.`id`
), 0)
) -
(coalesce((select max(`count`)
from table1 t_2
where t_2.`id` < (select max(`id`) from table1 t_1 where t_1.`id` < t.`id`)
), 0)
)
from table1 t
如果计数没有增加,那么您必须获取 id,然后再次加入值。多么有趣!这是代码:
select t.*,
coalesce(t1.count, 0) - coalesce(t2.count, 0)
from (select t.*,
(select max(`id`) as id1 from table1 t_1 where t_1.`id` < t.`id`
) as id1,
(select max(`count`) from table1 t_2
where t_2.`id` < (select max(`id`) from table1 t_1 where t_1.`id` < t.`id`)
) id2
from table1 t
) t left outer join
table1 t1
on t.id1 = t1.id left outer join
table1 t2
on t.id2 = t2.id