sqlserver LEAD和LAG函数
可用于sqlserver 2012以后的版本,主要是查询当前数据的前几条数据或后几条数据的值
例:
LAG函数 往上取,取前几条的数据
WITH T AS
(
SELECT 1 ID,10 NUM
UNION ALL
SELECT 1,20
UNION ALL
SELECT 1,30
UNION ALL
SELECT 2,40
UNION ALL
SELECT 2,50
UNION ALL
SELECT 2,60
)
SELECT
ID,
NUM,
LAG(NUM) OVER (PARTITION BY ID ORDER BY NUM) AS OneArgs,--根据id分组num排序,取上一条的记录
LAG(NUM,1) OVER (PARTITION BY ID ORDER BY NUM) AS TowArgs,--根据id分组num排序,取上一条的记录
LAG(NUM,2,0) OVER (PARTITION BY ID ORDER BY NUM) AS ThressArgs--根据id分组num排序,取上两条的记录,并且如果
共有 0 条评论