3

我有一个包含以下列的表

table: route
columns: id, location, order_id

它具有诸如

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

是否可以在 postgres 中执行一个 sql select 语句,该语句将返回每一行以及具有下一个最高 order_id 的 id?所以我想要类似...

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

谢谢

4

3 回答 3

6
select 
  id, 
  location, 
  order_id,
  lag(id) over (order by order_id desc) as next_id
from your_table
于 2012-04-27T10:31:52.023 回答
1

首先创建测试平台:

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);

查询:

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;

您可以在文档中阅读有关窗口函数的更多信息。

于 2012-04-27T10:32:32.813 回答
0

是的:

select * ,
(select top 1 id from routes_table where order_id > main.order_id order by 1 desc)
from routes_table main
于 2012-04-27T10:34:47.593 回答