不确定如何使用滞后功能获取数据。
我有此数据:
date value id
---------------------------------------
2019-03-01 00:00:00.000 1 a
2019-02-28 00:00:00.000 2 a
2019-02-27 00:00:00.000 3 a
2019-02-26 00:00:00.000 4 a
2019-03-01 00:00:00.000 4 b
2019-02-28 00:00:00.000 3 b
2019-02-27 00:00:00.000 2 b
2019-02-26 00:00:00.000 1 b
我需要lag 1和lag2值,并且每个id仅需要1行
id value lag1 lag2
--------------------
a 1 2 3
b 4 3 2
我的查询是
select
id, date, value,
lag(value, 1) over (partition by id order by date),
lag(value, 2) over (partition by id order by date)
from
data;
但是我得到的行多于1行,因此每行的滞后都会被计算出来。我知道函数的行为方式如此,但无法获得所需的输出。使用了另一个查询
select top 1
from
(select
id, date, value,
lag(value, 1) over (partition by id order by date),
lag(value, 2) over (partition by id order by date)
from
data)
这仅返回1行,但我有多个ID。我需要为每个ID限制1行。感谢您的帮助
答案 0 :(得分:0)
您可以进行聚合:
select t.id,
max(case when seq = 1 then value end) as value1,
max(case when seq = 2 then value end) as value2,
max(case when seq = 3 then value end) as value3,
max(case when seq = 4 then value end) as value4,
max(case when seq = 5 then value end) as value5
from (select t.*,
row_number() over (partition by id order by date desc) as seq
from table t
) t
group by t.id;
答案 1 :(得分:0)
lag()
是一个窗口函数,因此它不会更改行数。您需要进行一些过滤。
怎么样?
select id, date, value, value_1, value_2
from (select id, date, value,
lag(value, 1) over (partition by id order by
date) as value_1,
lag(value, 2) over (partition by id order by date) as value_2,
row_number() over (partition by id order by date desc) as seqnum
from data
) d
where seqnum = 1