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

SQL - How to get only current and previous value for each ID

我有一个table

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 日期,这是错误的) :

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

如何实现?

你可以试试下面的方法

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

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

create table a_test(id varchar(1), ddate date, value int);

insert into a_test values ('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);

with cte as(
select id,
       value,
       row_number() over(partition by id order by ddate desc) as rn
from a_test)

select id,
       MAX(value) FILTER (WHERE rn = 1) as col1,
       MAX(value) FILTER (WHERE rn = 2) as col2
from cte
group by id