具有
id | value
-----------
1 | 2
1 | 3
1 | 45
需要
id | value | value2
------------------------
1 | 2 | ---
1 | 3 | 2
1 | 45 | 3
--|---- | 45
你能展示变体,如何实现这一点吗?
您确实需要lag()
:
select id, value,
lag(value) over(partition by id order by value) value1
from mytable
在不支持窗口功能的数据库中,另一种选择是子查询:
select id, value,
(select max(value) from mytable t1 where t1.id = t.id and t1.value < t.value) value1
from mytable t
正确的方法是使用lag()
:
select id, value, lag(value) over (order by value) as prev_value
from t;
在不支持lag()
的数据库中,可以使用相关的子查询。类似于:
select t.*,
(select t2.value
from t t2
where t2.value < t.value
order by t2.value desc
fetch first 1 row only
) as prev_value
from t;
并非所有数据库都支持标准fetch first
,但所有数据库都应该具有类似的功能。