creating a pseudo linked list in sql

匿名 (未验证) 提交于 2019-12-03 03:03:02

问题:

I have a table that has the following columns

table: route columns: id, location, order_id 

and it has values such as

id, location, order_id 1, London, 12 2, Amsterdam, 102 3, Berlin, 90 5, Paris, 19 

Is it possible to do a sql select statement in postgres that will return each row along with the id with the next highest order_id? So I want something like...

id, location, order_id, next_id 1, London, 12, 5 2, Amsterdam, 102, NULL 3, Berlin, 90, 2 5, Paris, 19, 3 

Thanks

回答1:

select    id,    location,    order_id,   lag(id) over (order by order_id desc) as next_id from your_table 


回答2:

Creating testbed first:

CREATE TABLE route (id int4, location varchar(20), order_id int4); INSERT INTO route VALUES     (1,'London',12),(2,'Amsterdam',102),     (3,'Berlin',90),(5,'Paris',19); 

The query:

WITH ranked AS (     SELECT id,location,order_id,rank() OVER (ORDER BY order_id)       FROM route) SELECT b.id, b.location, b.order_id, n.id   FROM ranked b   LEFT JOIN ranked n ON b.rank+1=n.rank   ORDER BY b.id; 

You can read more on the window functions in the documentation.



回答3:

yes:

select * , (select top 1 id from routes_table where order_id > main.order_id order by 1 desc) from routes_table main 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!