Recursive query to give a route in postgreSQL - sql
I have to do a recursive function in pSQL to get the following query:
I have a table called tb_route with from_city and to_city
I have another column with the distance in km between different cities.
The table is builded recursively. I have to make a recursive CTE to show the route between two cities (i.e., from 'Santiago de compostela' to 'Saint Jean Pied de Port') showing the total km of the route and the cities where it goes through.
The output has to be something like this:
This is what I've tried:
WITH RECURSIVE cities AS (
SELECT *
FROM textil.tb_route
WHERE to_city_name = 'Santigo de Compostela'
UNION ALL
SELECT e.from_city, e.to_city, e.route, e.km
FROM textil.tb_route e
INNER JOIN cities tb_route ON tb_route.from_city_name = e.from_city
)
SELECT *
FROM cities;
And I had an error like:
ERROR: column e.from_city does not exist
LINE 8: ...JOIN cities tb_route ON tb_route.from_city_name = e.from_cit...
Table:
CREATE TABLE textil.tb_route
(
from_city_name CHARACTER VARYING(120) NOT NULL ,
to_city_name CHARACTER VARYING(120) NOT NULL ,
km_distance_num NUMERIC(5,2) NOT NULL ,
CONSTRAINT pk_route PRIMARY KEY (from_city_name, to_city_name)
);
Data:
INSERT INTO textil.tb_route VALUES
('Saint Jean Pied de Port','Roncesvalles',25.7),
('Somport','Jaca',30.5),
('Roncesvalles','Zubiri',21.5),
('Jaca','Arrés',25),
('Zubiri','Pamplona/Iruña',20.4),
('Arrés','Ruesta',28.7),
('Pamplona/Iruña','Puente la Reina/Gares',24),
('Ruesta','Sangüesa',21.8),
('Puente la Reina/Gares','Estella/Lizarra',22),
('Sangüesa','Monreal',27.25),
('Estella/Lizarra','Torres del Río',29),
('Monreal','Puente la Reina/Gares',31.1),
('Torres del Río','Logroño',20),
('Logroño','Nájera',29.6),
('Nájera','Santo Domingo de la Calzada',21),
('Santo Domingo de la Calzada','Belorado',22.7),
('Belorado','Agés',27.4),
('Agés','Burgos',23),
('Burgos','Hontanas',31.1),
('Hontanas','Boadilla del Camino',28.5),
('Boadilla del Camino','Carrión de los Condes',24.6),
('Carrión de los Condes','Terradillos de los Templarios',26.6),
('Terradillos de los Templarios','El Burgo Ranero',30.6),
('El Burgo Ranero','León',37.1),
('León','San Martín del Camino',25.9),
('San Martín del Camino','Astorga',24.2),
('Astorga','Foncebadón',25.9),
('Foncebadón','Ponferrada',27.3),
('Ponferrada','Villafranca del Bierzo',24.1),
('Villafranca del Bierzo','O Cebreiro',28.4),
('O Cebreiro','Triacastela',21.1),
('Triacastela','Sarria',18.3),
('Sarria','Portomarín',22.4),
('Portomarín','Palas de Rei',25),
('Palas de Rei','Arzúa',28.8),
('Arzúa','Pedrouzo',19.1),
('Pedrouzo','Santiago de Compostela',20),
('Bayona','Ustaritz',14.3),
('Ustaritz','Urdax',21.2),
('Urdax','Elizondo',18.8),
('Elizondo','Berroeta',9.7),
('Berroeta','Olagüe',20.4),
('Olagüe','Pamplona/Iruña',25),
('Irún','Hernani',26.6),
('Hernani','Tolosa',18.9),
('Tolosa','Zerain',33),
('Zerain','Salvatierra/Agurain',28),
('Salvatierra/Agurain','Vitoria/Gasteiz',27.4),
('Vitoria/Gasteiz','La Puebla de Arganzón',18.5),
('La Puebla de Arganzón','Haro',31),
('Haro','Santo Domingo de la Calzada',20),
('Bayona','Irún',33.8),
('Tolosa','Zegama',37.9),
('Zegama','Salvatierra/Agurain',20.1),
('La Puebla de Arganzón','Miranda del Ebro',22.3),
('Miranda del Ebro','Pancorbo',16.7),
('Pancorbo','Briviesca',23.4),
('Briviesca','Monasterio de Rodilla',19.8),
('Monasterio de Rodilla','Burgos',28.5);
```
Here I leave the solution I've get finally:
with recursive caminos(from_city_name, to_city_name, path, total_distance, terminar, ultima_ciudad) as (
-- Consulta base
select to_city_name
,'Saint Jean Pied de Port' -- Cambiar Destino
,concat(to_city_name, concat(' -> ', from_city_name))
,cast(km_distance_num as numeric(8,2))
,0 --No terminar
,from_city_name
from textil.tb_route
where to_city_name = 'Santiago de Compostela' -- Cambiar Origen
union all
-- Consulta recursiva
select caminos.from_city_name
,caminos.to_city_name
,concat(caminos.path, concat( ' -> ', tr.from_city_name))
,cast(caminos.total_distance + tr.km_distance_num as numeric(8,2))
,case when tr.from_city_name = caminos.to_city_name then 1 else 0 end
,tr.from_city_name
from caminos inner join textil.tb_route tr on tr.to_city_name = caminos.ultima_ciudad and caminos.terminar != 1
)
select from_city_name, to_city_name, path, total_distance
from caminos
where 1 = 1
and from_city_name = 'Santiago de Compostela' --Cambiar Origen
and ultima_ciudad = 'Saint Jean Pied de Port' -- Cambiar Destino
;
I understand your question as a graph-walking problem. As described in your questions, edges are directed (meaning that you can travel from from_city_name to to_city_name, but not the other way around).
Here is an approach using a recursive CTE. The idea is to start from a given city, and then follow all possible routes, while keeping track of the overall travel path in an arry. The recursion stops either when a circle is detected, or when the target city is reached. Then, the outer query filters on the successful paths (there may be none, one or several).
with recursive cte as (
select
from_city_name,
to_city_name,
km_distance_num,
array[from_city_name::text, to_city_name::text] path
from tb_route
where from_city_name = 'Saint Jean Pied de Port'
union all
select
r.from_city_name,
r.to_city_name,
c.km_distance_num + r.km_distance_num,
c.path || r.to_city_name::text
from tb_route r
inner join cte c on c.to_city_name = r.from_city_name
where
not r.to_city_name = any(c.path)
and c.from_city_name <> 'Santiago de Compostela'
)
select
path[1] from_city_name,
to_city_name,
km_distance_num,
array_to_string(path, ' > ') path
from cte
where to_city_name = 'Santiago de Compostela';
Demo on DB Fiddle:
from_city_name | to_city_name | km_distance_num | path
:---------------------- | :--------------------- | --------------: | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Saint Jean Pied de Port | Santiago de Compostela | 775.3 | Saint Jean Pied de Port > Roncesvalles > Zubiri > Pamplona/Iruña > Puente la Reina/Gares > Estella/Lizarra > Torres del Río > Logroño > Nájera > Santo Domingo de la Calzada > Belorado > Agés > Burgos > Hontanas > Boadilla del Camino > Carrión de los Condes > Terradillos de los Templarios > El Burgo Ranero > León > San Martín del Camino > Astorga > Foncebadón > Ponferrada > Villafranca del Bierzo > O Cebreiro > Triacastela > Sarria > Portomarín > Palas de Rei > Arzúa > Pedrouzo > Santiago de Compostela
Related
I am extracting data from a Json in SQL and the data comes in lists, how do I get it from there?
thanks for reading it! I am extracting data from a Json with operators in SQL, this is the code: select lc.name as company, lr.name as retailer, ls.name as tienda, sm.created_on as date, sm.task_id as task_id, ss.submission_data::json-> '¿Qué ''bancos'' se encuentran cerca de la tienda? De ser necesario, pregunta al gerente de tienda' AS banco, ss.submission_data::json->> 'Indica la distancia aproximada entre la tienda y el ''banco'' más cercano' AS banco_distancia, ss.submission_data::json->> '¿En la zona hay disponibilidad de ''transporte público''? Indica los tipos de transporte' AS transporte, ss.submission_data::json->> 'Indica el precio estimado de un viaje en ''transporte público''' AS transporte_precio, ss.submission_data::json->> '¿En la zona hay servicio de ''aplicaciones de envíos''?' AS app_envio from submission_submissionmetadata sm left join submission_submission ss on sm.submission_id = ss.id left join location_store ls on ls.id = sm.store_id left join location_retailer lr on lr.id = ls.retailer_id left join location_company lc on lc.id = lr.company_id where sm.brand_id = 293 order by date desc In The results I get the columns bank, transport and app_ship come as in a list type, I have tried to use functions to flatten this but I have not been successful. Do you know what I can do?
https://www.postgresql.org/docs/current/functions-json.html Waiting on your response to comment above, but you can see all the ways to extract json in the above doc. For instance,if you want only the first element of the app_envio array, it would be: ss.submission_data::json #>> '{'¿En la zona hay servicio de ''aplicaciones de envíos''?',0}' AS app_envio
Pascal sum calculator
What is the sum of this one (lets says that the value of x is 2) I have used pascal to solve this and this is Program Somme ; var n,factoriel,denominateur : longint ; Numerateur,x,x_sqr,somme_total:real; begin writeln('Bienvenue dans le programme : "La somme numerique".'); writeln(' '); write('Veuillez saisir la valeur numerique de x puis appuyez sur "entre" : '); read(x); somme_total:=0; x_sqr:= 1; factoriel:=1; for n:= 1 to 10 do begin factoriel:= factoriel*n; x_sqr:=x*x_sqr; Numerateur:= n+x_sqr; denominateur:=(2*factoriel)+1; somme_total:=somme_total + (Numerateur/denominateur); end; writeln('La somme total est : ',somme_total ) end. here is my teacher answer (I think that it's wrong) program Somme; uses wincrt; var n : integer; F,P,S,x,somme : real; Begin writeln ('Entrez la valeur de x '); readln(x); writeln ('===== Calcule de la Somme ====== '); writeln; F := 1; P := 1; S := 0; for n := 1 to 10 do begin F := F* n; P := P *x; S:= (n+P) / (2*F)+1; writeln ('Resultat de l étiration ', n, ' est égale: ', S:2:2); somme :=somme +S; end; writeln; writeln ('La somme S est égale: ', S:2:2); writeln; end. so which one is correct?
Access Query in Linq
I have a complex access sql query to transform in linq This is what I do : var query = from p in tbl_multiIntervenants.AsEnumerable() join q in ( from s in tbl_contrats.AsEnumerable() join t in ( from u in tbl_traitement_gapp.AsEnumerable() join v in tbl_TP.AsEnumerable() on u.Field<string>("Identifiant tâche") equals v.Field<string>("Identifiant tâche") into joined from jointe in joined.DefaultIfEmpty() select jointe ) ) Here the SQL query : SELECT Tbl_TP.Société, Tbl_TP.Région, Tbl_TP.[N° Site], Tbl_TP.[Nom Site], Tbl_TP.[Identifiant intervention], Tbl_TP.[Gamme intervention], Tbl_TP.[Description de l'intervention], Tbl_TP.[Identifiant tâche], Tbl_TP.Description, Tbl_TP.[Etat administratif intervention], Tbl_TP.[Date début prévu tâche], Tbl_TP.[Date fin prévu tâche], Tbl_TP.Detrompeur, Tbl_TP.[Entité demandeur], Tbl_TP.[Infos Demandeur], Tbl_TP.[Indicateur accompagnement], Tbl_TP.[Code Journalier], Tbl_TP.Coupure, Tbl_TP.[Validé ?], Tbl_TP.[Accompagnement ?], Tbl_TP.[Observation ?], Tbl_TP.Accès, Tbl_TP.[Contrainte de sécurité], Tbl_TP.V_Couleur, Tbl_TP.[Caractéristiques de l'intervention], Tbl_CONTRATS.[Sensibilité du site], Tbl_CONTRATS.[Approbation automatique AS], Tbl_TP.[Chef de projet SFR], Tbl_TP.[Date création intervention (hs)], Tbl_TP.[Identifiant demande], Tbl_TP.PlanPrevention, Tbl_CONTRATS.Appartenance FROM Tbl_Multi_Intervenants INNER JOIN (Tbl_CONTRATS INNER JOIN (Tbl_TP LEFT JOIN Tbl_Traitement_GAPP ON Tbl_TP.[Identifiant tâche] = Tbl_Traitement_GAPP.[Identifiant tâche]) ON Tbl_CONTRATS.Emplacement = Tbl_TP.[N° Site]) ON Tbl_Multi_Intervenants.[Identifiant tâche] = Tbl_TP.[Identifiant tâche] WHERE (((Tbl_Traitement_GAPP.[Identifiant tâche]) Is Null)) GROUP BY Tbl_TP.Société, Tbl_TP.Région, Tbl_TP.[N° Site], Tbl_TP.[Nom Site], Tbl_TP.[Identifiant intervention], Tbl_TP.[Gamme intervention], Tbl_TP.[Description de l'intervention], Tbl_TP.[Identifiant tâche], Tbl_TP.Description, Tbl_TP.[Etat administratif intervention], Tbl_TP.[Date début prévu tâche], Tbl_TP.[Date fin prévu tâche], Tbl_TP.Detrompeur, Tbl_TP.[Entité demandeur], Tbl_TP.[Infos Demandeur], Tbl_TP.[Indicateur accompagnement], Tbl_TP.[Code Journalier], Tbl_TP.Coupure, Tbl_TP.[Validé ?], Tbl_TP.[Accompagnement ?], Tbl_TP.[Observation ?], Tbl_TP.Accès, Tbl_TP.[Contrainte de sécurité], Tbl_TP.V_Couleur, Tbl_TP.[Caractéristiques de l'intervention], Tbl_CONTRATS.[Sensibilité du site], Tbl_CONTRATS.[Approbation automatique AS], Tbl_TP.[Chef de projet SFR], Tbl_TP.[Date création intervention (hs)], Tbl_TP.[Identifiant demande], Tbl_TP.PlanPrevention, Tbl_CONTRATS.Appartenance;
To simplify here is the sql query : SELECT Tbl_TP.Société, Tbl_CONTRATS.Appartenance FROM Tbl_Multi_Intervenants INNER JOIN (Tbl_CONTRATS INNER JOIN (Tbl_TP LEFT JOIN Tbl_Traitement_GAPP ON Tbl_TP.Identifiant tâche] = Tbl_Traitement_GAPP.[Identifiant tâche]) ON Tbl_CONTRATS.Emplacement = Tbl_TP.[N° Site]) ON Tbl_Multi_Intervenants.[Identifiant tâche] = Tbl_TP.[Identifiant tâche] WHERE (((Tbl_Traitement_GAPP.[Identifiant tâche]) Is Null))
SQL server Trigger no working
I create this trigger, and this select: SELECT #registro=seccion FROM dbo.horarios WHERE materia=#materia AND seccion=#seccionselect is not working. This link states that: if the value is not returned from select, previous assign value will be kept. But the record matching this criteria is not found it is returning new data. In the bottom is the output and database values. CREATE TRIGGER tgr_insertOnHorarios on horarios AFTER INSERT AS BEGIN DECLARE #materia varchar(7),#aula int,#profesor varchar(7), #seccion varchar(2),#dia varchar(10), #hora_desde time, #hora_hasta time, #cantidad int, #errores varchar(300), #displayError bit,#registro nchar(10) SELECT #materia= i.materia FROM inserted i; SELECT #profesor=i.profesor FROM inserted i; SELECT #seccion=i.seccion FROM inserted i; SELECT #dia= i.dia FROM inserted i; SELECT #hora_desde=i.hora_desde FROM inserted i; SELECT #hora_hasta= i.hora_hasta FROM inserted i; SELECT #cantidad= i.cantidad FROM inserted i; SELECT #aula = i.aula FROM inserted i; IF (SELECT cantidad_alumnos FROM aulas WHERE codigo=#aula)<#cantidad BEGIN SET #errores= 'Contiene mas estudiantes de los permitidos en el aula,' PRINT #errores --RAISERROR (#errores,16,1); ROLLBACK TRANSACTION; RETURN END print #seccion print #materia ***set #registro='empty'*** print 'registro '+ #registro **SELECT #registro=seccion FROM dbo.horarios WHERE materia=#materia AND seccion=#seccion** **print 'registro '+#registro** IF #registro = #seccion BEGIN SET #errores= ' La seccion y la materia ya esta creada, por favor, haga una nueva seccion' PRINT #errores --RAISERROR (#errores,16,1); ROLLBACK TRANSACTION; RETURN END -------------------------------------------- SELECT #registro=profesor FROM horarios WHERE dia=#dia AND hora_desde=#hora_desde AND #hora_hasta=hora_desde AND profesor=#profesor If #registro IS NOT NULL BEGIN SET #errores=' el profesor ya esta asignado en este horario' PRINT #errores --RAISERROR (#errores,16,1); ROLLBACK TRANSACTION; RETURN END -------------------------------------------- declare #dayassig varchar(10),#desde time,#hasta time SELECT #registro=profesor, #dayassig=dia,#desde=hora_desde,#hasta=hora_hasta FROM horarios WHERE #dayassig=#dia and ((#desde<=#hora_desde and #hasta>#hora_desde) OR (#desde<#hora_hasta and #hasta>=#hora_hasta)) IF #registro IS NOT NULL BEGIN SET #errores= #errores+' este horario choca' PRINT #errores --RAISERROR (#errores,16,1); ROLLBACK TRANSACTION; RETURN END END [output] 03 (printing input on insert seccion) CCI-110 (printing input on insert materia) registro **empty** (before select) registro **03** (after select, should not be returning this) La seccion y la materia ya esta creada, por favor, haga una nueva seccion [database values] materia aula profesor seccion dia hora_desde hora_hasta cantidad CCI-110 501 7722 01 miercoles 12:00:00.0000000 15:00:00.0000000 25 CCI-110 501 7722 01 miercoles 12:00:00.0000000 16:00:00.0000000 25 CCI-110 501 7722 01 miercoles 14:00:00.0000000 16:00:00.0000000 25 How you can see not record matching input seccion 03 andmateria CCI-110, but on [output is printing on register 03]?
Statement Error ORA-00923
i have a database that I have populated. I am now trying to write a SELECT statement: SELECT + FULL ( fst) full(fs) COUNT(DISTINCT r1.CLIENT_ID || e.CODE || fst.TAB_ID) NB_TAB FROM RATTACHEMENT_DART rd, FLUX_SORTANT fs, FS_TABLEAU fst, equipement e, REFERENTIEL r1, referentiel r2, referentiel pere; When I try to run the above case statement I recieve the following error: Erreur commençant à la ligne 4 de la commande : SELECT + FULL ( fst) full(fs) COUNT(DISTINCT r1.CLIENT_ID || e.CODE || fst.TAB_ID) NB_TAB FROM RATTACHEMENT_DART rd, FLUX_SORTANT fs, FS_TABLEAU fst, equipement e, REFERENTIEL r1, referentiel r2, referentiel pere Erreur à la ligne de commande : 4, colonne : 26 Rapport d'erreur : Erreur SQL : ORA-00923: mot-clé FROM absent à l'emplacement prévu 00923. 00000 - "FROM keyword not found where expected" *Cause: *Action:
If you want to use hints you should use /*+...*/ as below SELECT /*+ FULL( fst) full(fs)*/ COUNT(DISTINCT r1.CLIENT_ID || e.CODE || fst.TAB_ID) NB_TAB FROM RATTACHEMENT_DART rd, FLUX_SORTANT fs, FS_TABLEAU fst, equipement e, REFERENTIEL r1, referentiel r2, referentiel pere; See documentation