gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:19:01 27 4
gpt4 key购买 nike

我有一张 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

关于SQL - 如何仅获取每个 ID 的当前值和先前值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56263090/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com