gpt4 book ai didi

sql - 下一级别的 LAG()/LEAD() (Postgresql)

转载 作者:行者123 更新时间:2023-11-29 11:29:12 25 4
gpt4 key购买 nike

有什么方法可以强制 PostgreSQL LAG()LEAD() 函数使用的值不是来自前导行,而是同一分区的下一个等级?

---------------------------------------------------
| client_id | order_id | product_id | year | rank |
---------------------------------------------------
| 1 | 1 | 111345 | 1995 | 1 |
| 1 | 1 | 912346 | 1995 | 1 |
| 1 | 1 | 212346 | 1995 | 1 |
| 1 | 2 | 233368 | 1998 | 4 |
| 1 | 2 | 133368 | 1998 | 4 |
| 1 | 3 | 412341 | 2005 | 6 |
| 2 | 55 | 312344 | 1995 | 1 |
| 2 | 57 | 812343 | 1999 | 2 |
---------------------------------------------------

预期的结果是:

---------------------------------------------------------------------------
| client_id | order_id | product_id | year | rank | prev_year | next_year |
---------------------------------------------------------------------------
| 1 | 1 | 111345 | 1995 | 1 | null | 1998 |
| 1 | 1 | 912346 | 1995 | 1 | null | 1998 |
| 1 | 1 | 212346 | 1995 | 1 | null | 1998 |
| 1 | 2 | 233368 | 1998 | 4 | 1995 | 2005 |
| 1 | 2 | 133368 | 1998 | 4 | 1995 | 2005 |
| 1 | 3 | 412341 | 2005 | 6 | 1998 | null |
| 2 | 55 | 312344 | 1995 | 1 | null | 1999 |
| 2 | 57 | 812343 | 1999 | 2 | 1995 | null |
---------------------------------------------------------------------------

如果 year 在给定排名中有 distinct 值,则 prev_yearnext_year 可以是这些值中的任何一个。例如:

---------------------------------------------------------------------------
| client_id | order_id | product_id | year | rank | prev_year | next_year |
---------------------------------------------------------------------------
| 1 | 1 | 111345 | 1994 | 1 | null | 1998 |
| 1 | 1 | 912346 | 1995 | 1 | null | 1998 |
| 1 | 1 | 212346 | 1996 | 1 | null | 1998 |
| 1 | 2 | 233368 | 1998 | 4 | ???? | null |

???? 可以等于 1994、1995 或 1996

最佳答案

您应该在数据集上使用 lag()lead() 函数,每对 (client_id, rank) 减少到一行:

select 
client_id, order_id, product_id,
t.year, rank, prev_year, next_year
from my_table t
join (
select distinct on (client_id, rank)
client_id, rank, year,
lag(year) over w as prev_year,
lead(year) over w as next_year
from my_table
window w as (partition by client_id order by rank)
order by 1, 2, 3 desc
) s using (client_id, rank)
order by client_id, rank

client_id | order_id | product_id | year | rank | prev_year | next_year
-----------+----------+------------+------+------+-----------+-----------
1 | 1 | 212346 | 1995 | 1 | | 1998
1 | 1 | 912346 | 1995 | 1 | | 1998
1 | 1 | 111345 | 1995 | 1 | | 1998
1 | 2 | 133368 | 1998 | 4 | 1995 | 2005
1 | 2 | 233368 | 1998 | 4 | 1995 | 2005
1 | 3 | 412341 | 2005 | 6 | 1998 |
2 | 55 | 312344 | 1995 | 1 | | 1999
2 | 57 | 812343 | 1999 | 2 | 1995 |
(8 rows)

关于sql - 下一级别的 LAG()/LEAD() (Postgresql),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49534822/

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