Tengo una tabla que tiene las siguientes columnas
table: route columns: id, location, order_id
y tiene valores tales como
id, location, order_id 1, London, 12 2, Amsterdam, 102 3, Berlin, 90 5, Paris, 19
¿Es posible hacer una statement de selección sql en postgres que devolverá cada fila junto con la identificación con el siguiente order_id más alto? Entonces quiero algo como …
id, location, order_id, next_id 1, London, 12, 5 2, Amsterdam, 102, NULL 3, Berlin, 90, 2 5, Paris, 19, 3
Gracias
select id, location, order_id, lag(id) over (order by order_id desc) as next_id from your_table
Creando testbed primero:
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);
La consulta:
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;
Puede leer más sobre las funciones de la window en la documentation .
sí:
select * , (select top 1 id from routes_table where order_id > main.order_id order by 1 desc) from routes_table main