Finding Paths Between Two Nodes Using SQL Sorted by Cost

Hi Gurus,
I want to find all paths from source node to target node that shall be sorted by the cost. I don't know whether it could be achieved with SQL statement. How to start with this query? The script to create the underlying tables along with the data are given below:
create table nodes ( nodeId int Primary Key, nodeName varchar(50));
create table paths ( pathId int Primary Key, fromNodeId int, toNodeId int, cost int );
insert into nodes values (1,'ISL');
insert into nodes values (2,'LHR');
insert into nodes values (3,'HYD');
insert into nodes values (4,'FSL');
insert into nodes values (5,'MUL');
insert into nodes values (6,'KHI');
insert into nodes values (7,'QT');
insert into paths values (1,1,3,20);
insert into paths values (2,1,5,10);
insert into paths values (3,1,7,80);
insert into paths values (4,2,4,10);
insert into paths values (5,3,4,40);
insert into paths values (6,3,5,20);
insert into paths values (7,3,6,10);
insert into paths values (8,6,7,30);
insert into paths values (9,6,5,30);
insert into paths values (10,6,3,10);
insert into paths values (11,7,2,20);
insert into paths values (12,5,4,40);
insert into paths values (13,5,7,40);
Suppose the source = ISL and target = QT, their are various paths from ISL to QT:
Ord# Relative Path Cost
==== ================================= =================
1. ISL -> MUL -> QT 50
2. ISL -> HYD -> KHI -> QT 60
3. ISL -> QT 80
4. ISL -> HYD -> MUL -> QT 80
5. ISL -> HYD to KHI -> MUL -> QT 100
This gives us all possible paths sorted by cost.
Any hint or help will be highly appreciated.
Thanks in advance and best regards
Bilal
Edited by: naive2Oracle on Feb 11, 2011 9:59 AM

I like recursive with clause B-)
col path for a30
with nodes(nodeId,nodeName) as(
select 1,'ISL' from dual union
select 2,'LHR' from dual union
select 3,'HYD' from dual union
select 4,'FSL' from dual union
select 5,'MUL' from dual union
select 6,'KHI' from dual union
select 7,'QT'  from dual),
paths(fromNodeId,toNodeId,cost) as(
select 1,3,20 from dual union
select 1,5,10 from dual union
select 1,7,80 from dual union
select 2,4,10 from dual union
select 3,4,40 from dual union
select 3,5,20 from dual union
select 3,6,10 from dual union
select 6,7,30 from dual union
select 6,5,30 from dual union
select 6,3,10 from dual union
select 7,2,20 from dual union
select 5,4,40 from dual union
select 5,7,40 from dual),
tmp(nodeName,fromNodeId,toNodeId,cost) as(
select a.nodeName,b.fromNodeId,b.toNodeId,b.cost
  from nodes a,paths b
where a.nodeId=b.fromNodeId),
rec(nodeName,path,fromNodeId,toNodeId,cost) as(
select nodeName,cast(nodeName as varchar2(40)),
fromNodeId,toNodeId,cost
  from tmp
where nodeName = 'ISL'
union all
select b.nodeName,a.path || '->' || b.nodeName,
b.fromNodeId,b.toNodeId,
a.cost+decode(b.nodeName,'QT',0,b.cost)
  from rec a,tmp b
where a.toNodeId = b.fromNodeId
   and a.nodeName !='QT')
CYCLE fromNodeId SET IsLoop TO 'Y' DEFAULT 'N'
select path,cost from rec
where IsLoop ='N'
  and nodeName ='QT'
order by cost;
PATH                    COST
ISL->MUL->QT              50
ISL->HYD->KHI->QT         60
ISL->HYD->MUL->QT         80
ISL->QT                   80
ISL->HYD->KHI->MUL->QT   100

Similar Messages

  • Toplink cache synchronization between two nodes using tomcat

    Hi,
    In our appcation we have two nodes. Using websphere we used to synchronize toplink cache between two nodes. Can we do same thing using tomcat.

    Yes, TopLink implements cache synchronization using JMS or RMI easily, which are not dependent on the server being used - though it JMS especially does require a JMS provider that is accessible from each node.  Cache synchronization is now cache coordination, and is described using JPA properties here:
    http://wiki.eclipse.org/EclipseLink/Examples/JPA/CacheCoordination
    the Toplink cache synchronization/coordination with JMS | EMBARCADEROS seems to be a good read for cache coordination over JMS, but is more aimed at TopLink's sessions.xml configuration.
    Best Regards,
    Chris

  • Shortest path between two arbitrary point in the network

    Hi All,
    In oracle NDM, it's possible to find shortest path between two nodes (e.g. using SDO_NET_MEM.NETWORK_MANAGER.SHORTEST_PATH), but I need to find shortest path between 2 points which are on the network edges. I suppose I should use (Interface SubPath) in network java apis. However I want to do it via PLSQL api. Should I code it myself or there exists a function?
    Any help is appreciated.
    Edited by: Fa on Dec 15, 2011 2:51 AM

    pritamg wrote:
    I have to build an application in which the user will draw the graph by creating nodes and edges.and then the start node will be marked.Then the shortest paths to other nodes will be displayed.Give me any possible clue how to start.I am in deep deep trouble.I have to use Dijkstra's Algorithm.
    please help some one...pleaseDo you know Dijkstra's Algorithm for shortest path? I believe that one was also called the traveling salesman problem. You can easily Google to find out what it is.
    Did you listen to your instructor when he/she did his/her lectures on recursion and halting contitions? If not, then please go talk to him/her and read your book, the forum is not a place to try to learn a basic concept that you should have paid attention in class for the first time.
    If you have code and you have specific questions post them and we will be glad to help, but we are not here to develop your homework solutions for you, no matter how that may affect your future.

  • Network LOD support for All Paths between 2 nodes

    In the in-memory Network API, there is a method NetworkManager.allPaths. This method returns available paths between 2 nodes with possible constraints. I am looking for a similar method in the LOD NetworkAnalyst class and am not finding it. Is there something similar?
    Or, here is what I want to do, and maybe there is a better way to do it. I am using NDM to data-mine our roadway inventory. Its a big network, whole state of Ohio, all roads--both local and state. One of the things I am trying to identify are what we call co-located routes. These are routes that have multiple names, for example, the ohio turnpike is both Interstate 80 and 90 on the same bed of road. In our line work, where these routes are co-located, we would only have a record for 80. The portion of 90 that we would have would be only in the case where it is NOT co-located with 80; in other words, 90 has a gap where it is co-located with 80. This is true for all our roads. In this case, we call 80 the primary, and 90 the secondary. We can have infinite secondaries (our worst case scenario is 6 routes overlapping). My situation in many cases, is I know that a route becomes secondary, I know how long the secondary section is, but I don't know what the primary is, so I want to discover it.
    Given these assumptions, I should be able to ask for all paths between 2 nodes that exactly match a cost (the overall length of the overlap). This should be simple with NDM. I provide a begin node, an end node, and a target cost, possible some traversal constraints, and it returns me the candidate paths. I thought that NetworkAnalyst.withinCost would do this, but as I discovered from the Stored Procedure docs, it returns the shortest path within the given less than or equal to the given cost--not necessarily the path I am looking for.
    Any advice? FYI, I am using Oracle 11GR2.
    Thanks, Tom

    So what I have come up with so far, is that the NetworkAnalyst trace methods provide this type of functionality. For example, with traceOut, I provide a start node, distance and some traversal constraints, and it returns me all paths less than or equal to the specified distance. What was throwing me a little with this method was the application of the LODGoalNode. I was thinking that the goal node would allow me to specify a particular node to be a requirement for the entire path such that a resulting path would have my start node, and end on a particular goal node with links in between. That IS NOT how it works. The LODGoalNode.isGoal is tested for EACH link that is part of a potential path, and only if this method returns true, is it added to the resulting path list.
    In my case, if I specified a start node and implemented the LODGoalNode.isGoal method such that it tested the provided end node for equality to my target node, the result would be that only links containing that specific goal node in the link. Anyway, so in my implementation, I leave the goalNode of the traceOut method null.
    So I have a new question. Is there a way to test when a path has been found, and then apply some constraints on it (PathConstraint)? This would be useful in cases where you get many paths returned to you, but in addition to a maximum distance constraint, you also want to apply for example a minimum distance on the resulting path, or that this is only a valid path if it ends on a particular node. Maybe there is a way to do this, and I haven't figured it out yet. The old AnalysisInfo class used to have a way to query the current path links and nodes, that would be useful in the LODAnalysisInfo class to help accomplish this perhaps? This feature isn't critical, because I can filter the list of paths returned from traceOut on my own after they are returned, but it would add some efficiency, especially when a large amount of paths are returned.
    Thanks, Tom

  • Find gap between two dates from table

    Hello All,
    I want to find gap between two dates ,if there is no gap between two dates then it should return min(eff_dt) and max(end_dt) value
    suppose below data in my item table
    item_id    eff_dt           end_dt
    10         20-jun-2012     25-jun-2012
    10         26-jun-2012     28-jun-2012 There is no gap between two rows for item 10 then it should return rows like
    item_id eff_dt end_dt
    10 20-jun-2012 28-jun-2012
    item_id    eff_dt           end_dt
    12         20-jun-2012     25-jun-2012
    12         27-jun-2012     28-jun-2012 There is gap between two rows for item 12 then it should return like
    item_id eff_dt end_dt
    12 20-jun-2012 25-jun-2012
    12 27-jun-2012 28-jun-2012
    I hv tried using below query but it giv null value for last row
    SELECT   item_id, eff_dt, end_dt, end_dt + 1 AS newd,
             LEAD (eff_dt) OVER (PARTITION BY ctry_code, co_code, item_id ORDER BY ctry_code,
              co_code, item_id) AS LEAD,
             (CASE
                 WHEN (end_dt + 1) =
                        LEAD (eff_dt) OVER (PARTITION BY ctry_code, co_code, item_id ORDER BY ctry_code,
                         co_code, item_id, eff_dt)
                    THEN '1'
                 ELSE '2'
              END
             ) AS new_num
      FROM item
       WHERE TRIM (item_id) = '802'
    ORDER BY ctry_code, co_code, item_id, eff_dtI m using oracle 10g.
    please any help is appreciate.
    Thanks.

    Use start of group method:
    with sample_table as (
                          select 10 item_id,date '2012-6-20' start_dt,date '2012-6-25' end_dt from dual union all
                          select 10,date '2012-6-26',date '2012-6-26' from dual
    select  item_id,
            min(start_dt) start_dt,
            max(end_dt) end_dt
      from  (
             select  item_id,
                     start_dt,
                     end_dt,
                     sum(start_of_group) over(partition by item_id order by start_dt) grp
               from  (
                      select  item_id,
                              start_dt,
                              end_dt,
                              case lag(end_dt) over(partition by item_id order by start_dt)
                                when start_dt - 1 then 0
                                else 1
                              end start_of_group
                        from  sample_table
      group by item_id,
               grp
      order by item_id,
               grp
       ITEM_ID START_DT  END_DT
            10 20-JUN-12 26-JUN-12
    SQL> SY.

  • How to delete a path between two anchor points

    hi ,
    it's all in the title ,
    could you tell me  please how to delete a path between two anchor points without using the path eraser tool ?
    When I select these two anchor points and press delete everything is gone.
    ps : I want to keep the anchor points after the deletion
    Thank you

    Silkrooster wrote:
    With some experimentation, I did find that selecting the path can leave orphan points. So keep that in mind as it may be necessary to use Object>Path>Clean up...
    You will not get orphan points if you delete a segment that is not at the end of a path.  For segment that is at the end of a path, or is the entire path, select the end point/s and press delete. For the one segment that is entire path you can use the selection tool (black pointer) or hold Alt with the direct selection tool (white pointer) which is useful for objects in a group.

  • How to find differene between two time fields??

    Hi Experts,
    I am trying to find difference between two time fields,  I have created two formula variables by using replacement path for the two time fields, I have taken dimension key NUMBER, because of this time format is converting to numbers for example if the time is 13:20:10 then it is converting to 1,32,010 then it is calculating, I am getting wrong values.
    Is there any options to find out the difference between two time fields.
    Thanks in advance,
    Venkat.

    use COPF_DETERMINE_DURATION. Its better you do it in data model itself.
    If you have date and time seperately use command
    use CONVERT TIMESTAMP command and
    then use this function module to get the difference in
    timestamp
    CCU_TIMESTAMP_DIFFERENCE
    us this in conjunction with the below function module
    DAYS_BETWEEN_TWO_DATES
    Edited by: Ananda Theerthan on Jan 21, 2010 7:18 AM

  • How to create relationship between two records using MDM Java APIs

    Hi,
    I am trying to create relationship between two records using Java Apis. Please guide me in doing this.
    Regards,
    Niraj

    Hi Niraj,
    There is ModifyRelationshipsCommand:
    http://help.sap.com/javadocs/MDM/SP06/com/sap/mdm/data/commands/ModifyRelationshipsCommand.html
    Retrieve Relationship command:
    http://help.sap.com/javadocs/MDM/current/com/sap/mdm/schema/commands/GetRelationshipListCommand.html
    Also, please refer similar thread, MDM Java API and relationships.
    Hope it helps..
    Regards,
    Mandeep Saini

  • Finding Distance between two zipcodes with longtitude and latitude

    Want to find distance between two zipcodes that have their latitude and longitude stored in a table.
    The table is as follows
    CREATE TABLE distance (zipcode VARCHAR2, LNG NUMBER, LAT NUMBER)
    I couldn't come up with a calculation or understand the mathematical calculation on line.. Can you help me with some stored procedure that will do..?
    Thanks

    There is no logical complexity in your query besides knowing the basics of
    http://en.wikipedia.org/wiki/Spherical_coordinates
    Also, the table name "Distance" cannot be more confusing; what you have is essentially "PointsOnSphere".
    select R*sqrt(
    (sin(pi-p1.lng)*cos(p1.lat)-sin(pi-p2.lng)*cos(p2.lat))* (sin(pi-p1.lng)*cos(p1.lat)-sin(pi-p2.lng)*cos(p2.lat))
    +
    (sin(pi-p1.lng)*sin(p1.lat)-sin(pi-p2.lng)*sin(p2.lat))*
    (sin(pi-p1.lng)*sin(p1.lat)-sin(pi-p2.lng)*sin(p2.lat))
    +
    (cos(pi-p1.lng)-cos(pi-p2.lng))*(cos(pi-p1.lng)-cos(pi-p2.lng))
    from distance p1, distance p2
    where R is the radius of Earth, and pi=3. Don't forget to convert angular degrees into radiants before you plug in them into the query above
    Correction: This was euclidean distance sqrt((x1-x2)^2+(y1-y2)^2+(z1-z2)^2) between the points (x1,y1,z1) and (x2,y2,z2). Spherical distance is
    sqrt(
    (R*(colatitude1-colatitude2))^2+
    (R*sin(colatitude1-colatitude2)*(longtitude1-longtitude2))^2
    Message was edited by:
    Vadim Tropashko

  • How to draw a line(shortest distance)  between two ellipse using SWING

    how to draw a line(should be shortest distance) between two ellipse using SWING
    any help will be appreciated
    regards

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    public class ELine extends JPanel {
        Ellipse2D.Double red = new Ellipse2D.Double(150,110,75,165);
        Ellipse2D.Double blue = new Ellipse2D.Double(150,50,100,50);
        Line2D.Double line = new Line2D.Double();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.green.darker());
            g2.draw(line);
            g2.setPaint(Color.blue);
            g2.draw(blue);
            g2.setPaint(Color.red);
            g2.draw(red);
        private void connect() {
            double flatness = 0.01;
            PathIterator pit = blue.getPathIterator(null, flatness);
            double[] coords = new double[2];
            double x1 = 0, y1 = 0, x2 = 0, y2 = 0;
            double min = Double.MAX_VALUE;
            while(!pit.isDone()) {
                int type = pit.currentSegment(coords);
                switch(type) {
                    case PathIterator.SEG_MOVETO:
                    case PathIterator.SEG_LINETO:
                        Point2D.Double p = getClosestPoint(coords[0], coords[1]);
                        double dist = p.distance(coords[0], coords[1]);
                        if(dist < min) {
                            min = dist;
                            x1 = coords[0];
                            y1 = coords[1];
                            x2 = p.x;
                            y2 = p.y;
                        break;
                    case PathIterator.SEG_CLOSE:
                        break;
                    default:
                        System.out.println("blue type: " + type);
                pit.next();
            line.setLine(x1, y1, x2, y2);
        private Point2D.Double getClosestPoint(double x, double y) {
            double flatness = 0.01;
            PathIterator pit = red.getPathIterator(null, flatness);
            double[] coords = new double[2];
            Point2D.Double p = new Point2D.Double();
            double min = Double.MAX_VALUE;
            while(!pit.isDone()) {
                int type = pit.currentSegment(coords);
                switch(type) {
                    case PathIterator.SEG_MOVETO:
                    case PathIterator.SEG_LINETO:
                        double dist = Point2D.distance(x, y, coords[0], coords[1]);
                        if(dist < min) {
                            min = dist;
                            p.setLocation(coords[0], coords[1]);
                        break;
                    case PathIterator.SEG_CLOSE:
                        break;
                    default:
                        System.out.println("red type: " + type);
                pit.next();
            return p;
        public static void main(String[] args) {
            final ELine test = new ELine();
            test.addMouseListener(test.mia);
            test.addMouseMotionListener(test.mia);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(test);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    Graphics g = test.getGraphics();
                    g.drawString("drag me", 175, 80);
                    g.dispose();
        private MouseInputAdapter mia = new MouseInputAdapter() {
            Point2D.Double offset = new Point2D.Double();
            boolean dragging = false;
            public void mousePressed(MouseEvent e) {
                Point p = e.getPoint();
                if(blue.contains(p)) {
                    offset.x = p.x - blue.x;
                    offset.y = p.y - blue.y;
                    dragging = true;
            public void mouseReleased(MouseEvent e) {
                dragging = false;
            public void mouseDragged(MouseEvent e) {
                if(dragging) {
                    double x = e.getX() - offset.x;
                    double y = e.getY() - offset.y;
                    blue.setFrame(x, y, blue.width, blue.height);
                    connect();
                    repaint();
    }

  • Is there any way to enable eventlog replication between two nodes in windows 2008 failover cluster.

    Is there any way to enable eventlog replication between two nodes in windows 2008 failover cluster.
    Thanks Azam When you see answers please Mark as Answer if Helpful..vote as helpful.

    Hi,
    As far as I know there don’t have the log replica function between failover cluster node, if you want to have the Unified log management you can refer the following related
    KB:
    Configure Computers to Forward and Collect Events
    http://technet.microsoft.com/en-us/library/cc748890.aspx
    Hope this helps.
    We
    are trying to better understand customer views on social support experience, so your participation in this
    interview project would be greatly appreciated if you have time.
    Thanks for helping make community forums a great place.

  • How can I remove all content between two tags using Find/Replace regular expressions?

    This one is driving me bonkers...  I'm relatively new to regular expressions, but I'm trying to get Dreamweaver to remove all content between two tags in an XML document.  For example, let's say I have the following XML:
    <custom>
    <![CDATA[<p>Some text</p>
    <p>Some more text</p>]]>
    </custom>
    I'd like to do a Find/Replace that produces:
    <custom>
    </custom>
    In essence, I'd like to strip all of the content between two tags.  Ideally, I'd like to know how to strip the CDATA content as well, to return the following:
    <custom>
    <![CDATA[]]>
    </custom>
    I'd much appreciate any suggestions on accomplishing this.
    Many thanks!

    Thanks much for your response.  I found David's article to be a little thin with respect to examples using quantifiers in coordination with the wildcard metacharacters; however, I was able to cobble together a working expression through trial and error using the information he presented.  For posterity, here’s the solution:
    Find:
    <custom>[\d\D]*?</custom>
    Replace:
    <custom>
    <![CDATA[]]>
    </custom>
    I believe this literally translates to:
    [] = find anything in this range/character class
    \d = find any digit character (i.e. any number)
    \D = find any non-digit character (i.e. anything except numbers)
    *? = match zero or more times, but as few times as possible (i.e. match multiple characters per instance, but only match one instance at a time, or none at all)
    I’m still not sure how to effectively utilize the . wildcard.  For example, the following expression will not find content that ends with a number:
    <custom>.*?[\D]*?</ custom >
    I'm presuming this is because numbers aren't included in the \D metacharacter; however, shouldn't numbers be picked up by the .*? expression?

  • How to find the phase difference between two signals using Hilbert transform

    hi, 
        I am new to LabView.... I am trying to find phase difference between two signals. I sucessfuly found out the phase difference between two predefined waves using single tone measurement. .... But I really want to know how can I measure phase difference between two signals( not predefined... ie we don't know the initial conditions) using hilbert transform or any transformation techniques (without using zero cross detection).. I tried by using hilbert transform based on algorithm... bt I am getting error.... plz help me
    Attachments:
    phase_differece.vi ‏66 KB

    you could try something similar to this, for each table pair that you want to compare:
    SELECT 'TABLE_A has these columns that are not in TABLE_B', DIFF.*
      FROM (
            SELECT  COLUMN_NAME, DATA_TYPE, DATA_LENGTH
              FROM all_tab_columns
             WHERE table_name = 'TABLE_A'
             MINUS
            SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH
              FROM all_tab_columns
             WHERE table_name = 'TABLE_B'
          ) DIFF
    UNION
    SELECT 'TABLE_B has these columns that are not in TABLE_A', DIFF.*
      FROM (
            SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH
              FROM all_tab_columns
             WHERE table_name = 'TABLE_B'
             MINUS
            SELECT COLUMN_NAME, DATA_TYPE, DATA_LENGTH
              FROM all_tab_columns
             WHERE table_name = 'TABLE_A'
          ) DIFF;that's assuming, column_name, data_type and data_length are all you want to compare on.

  • Using VMware Not ping between two nodes.

    Dear All,
    I am installing the Linux and Installing the RAC using VMWare. Shared disk and all things were done. But not ping between the two nodes.
    Regards
    Prasannavenkatesh.K

    I have previously made entry in /etc/hosts file.
    now i am able to ping all the nodes no problem
    thnks
    now i have a problem in installing oracle crs in RAC1
    I login to RAC1 as the oracle user and start the Oracle CRS installer
    and while the specify the cluster configuration screen, i came across the error
    "The installer has detected the existence of 10g oracle
    clusterware on the remote node rac2 however, 10g oracle doesn't exist in the local node If
    u wish to upgrade and existing 10g release 2 ,then u must start the installer on a mode "
    thnks in anticipation
    prassana

  • All Paths between 2 Nodes

    Hi ,
    Can someone please let me know how I could be achieving this?
    I want to find out all the paths between the Source Node A and the Destination Node B.
    I donot want the shortest path but all the paths between the 2 nodes.
    Also I donot have any weight/cost associated with any path. ( Graph is a directed graph)
    Regards,
    Akshatha

    Hi,
    Maybe this :Scott@my11g SQL>l
      1  with links(n1,n2) as (
      2  select 'A','B' from dual
      3  union all select 'A','C' from dual
      4  union all select 'B','C' from dual
      5  union all select 'B','D' from dual
      6  union all select 'D','G' from dual
      7  union all select 'C','G' from dual
      8  union all select 'D','I' from dual
      9  union all select 'C','E' from dual
    10  union all select 'E','F' from dual
    11  union all select 'F','G' from dual
    12  union all select 'F','H' from dual
    13  )
    14  select pth
    15  from (
    16  select connect_by_root(n1) || sys_connect_by_path(n2,'>') pth ,n2
    17  from links
    18  start with n1='A'
    19  connect by nocycle prior n2=n1
    20  )
    21* where n2='G'
    Scott@my11g SQL>/
    PTH
    A>B>C>E>F>G
    A>B>C>G
    A>B>D>G
    A>C>E>F>G
    A>C>G

Maybe you are looking for