SQL-如何仅获取每个ID的当前值和先前值

时间:2019-05-22 18:42:01

标签: sql snowflake

我有一张桌子

id, date, value
a,  5/22/2019, 22
b,  5/22/2019, 22
c,  5/22/2019, 22
a,  5/21/2019, 21
b,  5/21/2019, 21
c,  5/21/2019, 21
a,  5/20/2019, 20
b,  5/20/2019, 20
c,  5/20/2019, 20

想要获取当前(最新)和上一个日期的ID和值:

id, date, date-1
a, 22, 21
b, 22, 21
c, 22, 21

到目前为止,我有一些部分,但每行仅需要1个ID(此波纹管为每个ID提供多于1行-对于同一ID,它将在下一行显示5/20日期,这是错误的):< / p>

select 
    id, value,
    lag(value, 1, 0) over (partition by id order by date ) as "date - 1"
from 
    table1

如何实现?

2 个答案:

答案 0 :(得分:1)

您可以尝试以下操作

with cte as
(
select 
    id, value,
    lag(value, 1, 0) over (partition by id order by date ) as "date - 1",
    lag(value, 2, 0) over (partition by id order by date ) as "date - 2",
    row_number() over(partition by id order by date desc) rn
from 
    table1
) select * from cte where rn=1

答案 1 :(得分:1)

这个怎么样?请注意,我将列命名为XMLHttpRequest而不是日期:

ddate