[英]Sum() in Oracle SQL connect by
I am trying to solve oracle SQL
scenario. 我正在尝试解决oracle SQL
场景。 I have to find all possible path between two places and calculate the total distance between them , number of stops between the two places and the path, using SQL
query.The Source table contains 3 columns
ie Departure_city , Arrival_City and Distance
. 我必须找到两个地方之间的所有可能路径并使用SQL
查询计算它们之间的总距离,两个地点之间的停靠点数和路径。源表包含3 columns
即Departure_city , Arrival_City and Distance
。
I wrote a SQL query and founded the number of stops and the path.But I couldn't find the total distance. 我写了一个SQL查询,并建立了停止次数和路径。但我找不到总距离。 My Query is: 我的查询是:
select * from(select arrive , level-1 , sys_connect_by_path (depart ,',')
from travel
start with depart = 'Mexico'
connect by nocycle prior arrive=depart)
where arrive = 'New York';
Here I took Delhi
as Departure_city
and Bangalore
as Arrival city
. 在这里,我将Delhi
作为Departure_city
和Bangalore
作为Arrival city
。
You can try dynamic evaluation or subquery factoring. 您可以尝试动态评估或子查询因子分解。 Take a look 看一看
This is kind of tricky, since you want to get the sum
for the path taken by the recursive query. 这有点棘手,因为您希望得到递归查询所采用路径的sum
。 This solution is a little unorthodox, but should work: 这个解决方案有点不正统,但应该有效:
CREATE OR REPLACE FUNCTION prod.eval (p_equation VARCHAR2)
RETURN NUMBER IS
v_result NUMBER;
BEGIN
IF LENGTH (TRIM (TRANSLATE (p_equation, '1234567890+-()*/', ' ')))
IS NOT NULL THEN
raise_application_error (
-20000,
'EVAL: Parameter contains non mathematical values');
END IF;
EXECUTE IMMEDIATE ' begin :1 := ' || p_equation || '; end;'
USING OUT v_result;
RETURN v_result;
END;
/
select * from(select arrive ,
level-1 ,
sys_connect_by_path (depart ,',') as hops
eval('0' || sys_connect_by_path (distance ,'+')) as distance
from travel
start with depart = 'Delhi'
connect by nocycle prior arrive=depart)
where arrive = 'Bangalore';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.