SQL SELECT to hierarchical tables: START WITH... CONNECT BY...

This seems to be a simple problem, but I think that I have enough intelligence SQL to solve.

I have a table called DE_DOMAIN. The columns of interest are:
DOMAIN_ID - PK
NAME
PARENT_ID - FK (can be NULL), poining to CF of the parent

What I want is: Returns a hierarchical list, containing: column 3 above as well as the NAME of the parent.

Regardless of the name of the parent, it works fine:
SELECT DOMAIN_ID, PARENT_ID, level
OF DE_DOMAIN
WHERE SUPERDOMAINE = 2673
Start by PARENT_ID IS NULL
Connect DOMAIN_ID PARENT_ID = prior
BROTHERS AND SŒURS ORDER BY NAME ASC

and I get:
11 rec_11 1 Null
15 rec_15 1 Null
16 1 Null rec_16
17 1 Null rec_17
22 17 2 rec_22
1 2 17 rec_1
rec_25 25 17 2
2 2 17 rec_2

i.e. records with PK = 1, 22, 25, 2 have all like parent record with PK = 17, then the new column name, they must bear the name of the parent (i.e. rec_17).

A simple idea?
Thank you very much.

Hello

You can use the FIRST operator in the SELECT clause.
I don't have a version of your table, so I'll use scott.emp to illustrate:

SELECT     empno
,     ename
,     mgr
,     PRIOR ename    AS mgr_name
FROM     scott.emp
START WITH     mgr     IS NULL
CONNECT BY     mgr     = PRIOR empno
ORDER SIBLINGS BY     ename
;

Output:

.    EMPNO ENAME             MGR MGR_NAME
---------- ---------- ---------- ----------
      7839 KING
      7698 BLAKE            7839 KING
      7499 ALLEN            7698 BLAKE
      7900 JAMES            7698 BLAKE
      7654 MARTIN           7698 BLAKE
      7844 TURNER           7698 BLAKE
      7521 WARD             7698 BLAKE
      7782 CLARK            7839 KING
      7934 MILLER           7782 CLARK
      7566 JONES            7839 KING
      7902 FORD             7566 JONES
      7369 SMITH            7902 FORD
      7788 SCOTT            7566 JONES
      7876 ADAMS            7788 SCOTT

Tags: Database

Similar Questions

  • Application of the terms of registration parent when you use START WITH / CONNECT BY FRONT

    Hello

    I'm trying to understand how to apply when only apparent conditions when using records to begin with... connect by prior logic.

    Here is an example...

    Table:
    CREATE TABLE TEMP_BTL
    (
      TRANS_ID               NUMBER(22,20),
      PARENT_TRANS_ID  NUMBER(22,20),
      TYPE_ID                 NUMBER,
      STATUS_ID             NUMBER
    );
    Records:
    SET DEFINE OFF;
    Insert into TEMP_BTL
       (TRANS_ID, PARENT_TRANS_ID, TYPE_ID, STATUS_ID)
     Values
       (1, NULL, 1, 2);
    Insert into TEMP_BTL
       (TRANS_ID, PARENT_TRANS_ID, TYPE_ID, STATUS_ID)
     Values
       (2, 1, 2, 1);
    Insert into TEMP_BTL
       (TRANS_ID, PARENT_TRANS_ID, TYPE_ID, STATUS_ID)
     Values
       (3, 2, 3, 4);
    Insert into TEMP_BTL
       (TRANS_ID, PARENT_TRANS_ID, TYPE_ID, STATUS_ID)
     Values
       (4, 3, 4, 3);
    Insert into TEMP_BTL
       (TRANS_ID, PARENT_TRANS_ID, TYPE_ID, STATUS_ID)
     Values
       (5, NULL, 2, 3);
    Insert into TEMP_BTL
       (TRANS_ID, PARENT_TRANS_ID, TYPE_ID, STATUS_ID)
     Values
       (6, 5, 4, 1);
    Insert into TEMP_BTL
       (TRANS_ID, PARENT_TRANS_ID, TYPE_ID, STATUS_ID)
     Values
       (7, 6, 5, 3);
    Insert into TEMP_BTL
       (TRANS_ID, PARENT_TRANS_ID, TYPE_ID, STATUS_ID)
     Values
       (8, 7, 6, 2);
    Insert into TEMP_BTL
       (TRANS_ID, PARENT_TRANS_ID, TYPE_ID, STATUS_ID)
     Values
       (9, NULL, 1, 3);
    If my query rules are:

    PARENT_TRANS_ID IS NULL = parent_record

    I have to limit my results so that only considered hierarchical groups are groups that record the type_id of the parent = 1 (single parent record limit to this condition, no children)

    Then I need to find the max (trans_id) of each subset for groups where the parent record type_id = 1

    Thus, according to the data from the example above, would be results that I would look:

    TRANS_ID = 1 group parent, I don't want to return trans_id = 4

    I would not return anything for the trans_id = 5 parent group because the type_id of that parent is not 1

    For trans_id 9, is the parent and the only record for this group so it is type_id = 1 I'm not going back 9 as the max (trans_id) for this game.

    And then, eventually, I'll limit my results to the place where the max id batch trans = 3.

    Any help is appreciated...

    Thank you
    Christine

    Hi, Christine.

    cad0227 wrote:
    Hello

    I'm trying to understand how to apply when only apparent conditions when using records to begin with... connect by prior logic.

    In your example of data 2 is the parent of 3, and 3 is the parent of 4.
    Use 'root' to describe nodes (for example, 1 and 5) that have no parents.

    Here is an example...

    Table:

    CREATE TABLE TEMP_BTL ...
    

    Thank you for including CREATE TABLE and INSERT statements. It's very useful!

    If my query rules are:

    PARENT_TRANS_ID IS NULL = parent_record

    I have to limit my results so that only considered hierarchical groups are groups that record the type_id of the parent = 1 (single parent record limit to this condition, no children)

    The START WITH clause is where to put the conditions that apply only to the roots.

    Then I need to find the max (trans_id) of each subset for groups where the parent record type_id = 1

    Thus, according to the data from the example above, would be results that I would look:

    TRANS_ID = 1 group parent, I don't want to return trans_id = 4

    I would not return anything for the trans_id = 5 parent group because the type_id of that parent is not 1

    For trans_id 9, is the parent and the only record for this group so it is type_id = 1 I'm not going back 9 as the max (trans_id) for this game.

    And then, eventually, I'll limit my results to the place where the max id batch trans = 3.

    Any help is appreciated...

    It would be useful that you reported the exact output desired. Describing the output is great, especially when it is as clear as your description, but describe the results, in addition to, not instead not to display.
    Here are the results you want?

    `  ROOT_ID MAX_TRANS_ID
    ---------- ------------
             1            4
             9            9
    

    Here's a way to get them:

    WITH     got_root_id     AS
    (
         SELECT     trans_id
         ,     CONNECT_BY_ROOT trans_id          AS root_id
         FROM     temp_btl
         WHERE     status_id     = 3
         START WITH     type_id          = 1
                     AND     parent_trans_id     IS NULL
         CONNECT BY     parent_trans_id     = PRIOR trans_id
    )
    SELECT       root_id
    ,       MAX (trans_id)     AS max_trans_id
    FROM       got_root_id
    GROUP BY  root_id
    ;
    

    Published by: Frank Kulash on 13 August 2012 13:58

  • G5 Powerpc does not start with connected external USB

    Core PowerPC G5 2.3 duel starts when I have my usb external 500 GB on drive but it works perfectly well if I boot

    with it goes off and then start and turned on after my mac started in Leopard 10.5.8 external USB is a 500 MB TARGA

    I have a WD elements 2. TB disk connected as well and I have no problem with it, it's a pain to remember to put a stop on all the time.

    Anyone have any ideas on that.

    Drive external hard there an independent supply?

    What happens if you attach externally to a different USB port?

  • Satellite Pro U400-11V - Sharp noise when starting with connected screen

    Hello

    We received 5 x computers laptops Satellite Pro U400-11V, are excellent, with one exception:

    When you start (it happens on all of them) with a screen VGA monitor plugged in, a high beep is played from what looks like the speaker system. It occurs just before the first splash screen windows.

    Once the windows login screen is displayed a monitor can be connected to any problem & works very well.

    What can I check? I have had a look but do not find all the tracks so far, where this post.

    Thank you
    -A

    Perhaps you are meaning that the beep POST (Power on self test)?

    The laptop still sounds if the POST has been successfully passed.

    Parts of the motherboard will be verified during POST, and if everything is ok, a beep is displayed.

    If something would be a mistake, the laptop will not start and different beeps would appear.

    Welcome them

  • HP envy Phoenix: win 7 does not start with connected external hard drive

    I have a desktop HP Envy Phoenix with i7 chip and an SSD for the OS.  If I connect via USB external drive of 3 TB WD for the backup of the system does not start while it is attached.  The pc seems to be trying to boot from the outside, can't find the OS and does not start.  It will start fine with small external drives connected.  It is the size of the disk? Is there a way to fix this?

    Hello

    The WD drives seem to pose problems of my potential.  I have used other brands such as Seagate and Hitachi without running into problems with external USB drives causing the system to boot.  Maybe it's the USB adapter that I use which does not cause starting problems.

    @tpetras

    I used the adapter HP USB 3, which uses drivers NEC or TI and has never had a problem starting via a USB external (non - WD) readers.

  • Computer does not start with connected external HARD disk

    Although my BIOS doesn't look like another hard drive, when I start my computer with the external hard drive, the main computer shuts down until I have disable externally. I want to have external to back up automatically but can not have both to play well.

    Help!

    Hello

    The same thing happened on my laptop with a connected external printer.
    I was not able to turn on the laptop until I unplugged the USB printer.

    Well, I checked the BIOS which controls the start and put the HARD internal disk to the first position!
    Try this. Maybe it helps. Otherwise you will need to disconnect the external USB HDD til the operating system has started

  • TS430 does not start with connected USB drive?

    I'm upgrading to a TS430 where I could plug the USB and restart without problems, after upgrading to the TS440 is more an option so if I want to leave a disc in to make backups that will simply not work...

    I tried updating to the latest version of the BIOS no luck, the TS140 seems to have the same problem.

    http://forums.Lenovo.com/T5/ThinkServer-towers/TS140-will-not-boot-with-external-HDD-attached/TD-p/1...

    Simply delayed! I tried the USB keys, WD drive and disk Seagate, and USB HD Caddy all stop to start!

    Note of the moderator; issue published; T430 was t440


  • Compilation error in tables starting with "number of months".

    Our project currently uses two entities: global (the family) and the person.

    I'm unable to compile a document when using a variable number that begins with "the number of months the person...". "in a table. For example, I tried to use this table to set the period of time to 0 in case "the person" does not request specific supplement type:

    --------------------------------------------------------------------------------------------------------------------------------------------------------------------
    Conclusion of the table:
    the number of months that the person will receive the supplement for assistance with associated transportation costs and visitors who attend the related program of employment

    Return value:
    the number of months the person to receive further assistance for transport and attendance costs to participate in the program related to employment

    If the following attribute is set to True:
    Supplement of the person is using to transport costs and traffic associated with participating in the program related to employment

    Otherwise:
    * 0 *
    --------------------------------------------------------------------------------------------------------------------------------------------------------------------


    The error I'll be back when you try to compile said: error after "number of". Found: «months that the person has applied to receive a supplement...» ». Expected: Unable to find a relationship of belonging to the entity "the person".

    However, I am able to compile the same attribute when it is written in the typical word format.



    I found two workaround solutions:

    (1) I cannot change variables numbers as follows: "the requested person several months to receive a supplement...» »
    (2) I can compile and generate if I write the attribute at the global level: "the number of moths the supplement for assistance... will be issued".

    Is anyone know why I get the above error?



    Thank you
    Ashley

    Have a variable whose text begins by "the number of ' is not a problem. I think that your problem here, is that the variables have not been declared.

    I just tried the table you have described above. When all variables are declared, they compile not very well. When one or both of the variables have not been reported, I got an error message similar to the one you have seen.

    See you soon,.
    Jasmine

  • SatelliteU300 will not start with power connected and fully charged battery

    I just bought a U300-13U. It works fine when charging the battery and AC is connected. However, if left to recharge completely it does not start with connected AC. Unpluging the power or remove the battery and running on AC make it work very well. Is a 'feature' to stop an overload or overheating of the battery, or just a problem with this machine. I want to run with AC and battery than both connected all the time like I did with all my other laptops.

    Any help appreciated.

    Hello Andy

    Of my friends has this small U300 and everything works well. I got it a few weeks ago to test the family Windows XP Setup and it works perfectly.

    Please test again very carefully and if the same thing happen again once I recommend you contact the Service partner in your country. They check your laptop. I have to be honest and say that describes the problem of strange sounds to me and please, don't wait too long. Contact the service as soon as possible.

    Bye and good luck!

  • computer a824n of office doesn't start with an external hard drive 2T connected.

    My HP Pavilion a824n desktop computer won't start with my new external hard drive 2T connected via a USB port.  The computer stops on the first screen, which I think is the Intel screen, with options for press ESC, F1, F10.  But these keys do nothing.  The only way out is to press the power button until the computer turns off.

    If I disconnect the external drive before turning the power on, the computer starts normally, the internal hard drive.  After that, I can connect from the outside and it works correctly, so I don't think that there is a defect in it.

    I can get into the screen of the BIOS settings to start with the external drive disconnected and by pressing the F8 key.  But the BIOS shows adequate priority, with the hard drive screen internal first, second DVD, third CD.  The internal hard drive is correctly identified by the model number and the new external drive is not at all (because I started without the connected external.)

    My guess is that when I start with connected externally, BIOS thinks it's the hard drive, it is supposed to boot from.  How can I get the machine to boot from the internal drive?

    Your guess is correct. The hard part is that I'm not sure of an exact solution I've seen this be something difficult to solve.

    Have you tried to update the firmware of an external drive?

    Have you updated your PC BIOS? If you are still running XP, I think that it is the update to the BIOS of your PC:

    http://h10025.www1.HP.com/ewfrf/WC/softwareDownloadIndex?softwareitem=PV-40501-1&CC=US&DLC=en&LC=en&os=228&Product=445596&sw_lang=

  • START WITH and CONNECT BY in Oracle SQL (hierarchical)

    Hi, the original table as below
    Customer_ID         Account_ID          Paying_Account_ID         Parent_Account_ID          Company_ID
    158                    158                    158                         158                     0
    159                    159                    158                         158                     0
    160                    160                    158                         158                     0
    181                    181                    181                         181                     0
    183                    183                    183                         183                     0
    24669                  24669                  24669                       24669                   0         
    24671                  24671                  24671                       24669                   0
    24670                  24670                  24670                       24669                   0     
    3385127                3385127                3385127                     24670                   0
    To identify the hierarchical relationship of the data, which are PARENT_ACCOUNT_ID & ACCOUNT_ID, here's the query I used.
     select  lpad(' ', 2*level) || A.ACCOUNT_ID AS LEVEL_LABEL, CONNECT_BY_ISCYCLE "Cycle", LEVEL, A.* from ACCOUNT A
    START WITH parent_account_id = account_id
    CONNECT BY NOCYCLE  PRIOR A.ACCOUNT_ID = A.PARENT_ACCOUNT_ID
    AND account_id != parent_account_id
    ;
    It is the result of the query
    Level_Label              Level          Cycle        Customer_ID             Account_ID        Paying_Account_ID      Parent_Account_ID      Company_ID
    158                         1             0              158                     158              158                   158                     0
       159                      2             0              159                     159              158                   158                     0
       160                      2             0              160                     160              158                   158                     0
    181                         1             0              181                     181              181                   181                     0
    183                         1             0              183                     183              183                   183                     0
    24669                       1             0              24669                   24669            24669                 24669                   0       
        24671                   2             0              24671                   24671            24671                 24669                   0
        24670                   2             0              24670                   24670            24670                 24669                   0
            3385127             3             0              3385127                 3385127          3385127               24670                   0
    My question is how can I changed the query to calculate the values for:

    My_Total_PR - number of my accounts to child PR which do not include himself.
    Total_PR - Total number of accounts PR in the overall structure
    My_Total_NPR - number of my accounts of child NPR which do not include himself.
    Total_NPR - Total number of accounts NPR in the overall structure

    * PR stand for responsible for payment, for example the responsible account payment 158 158 (Paying_Account_ID), therefore the Total_PR to 158 is 3 (158, 159, 160)
    * NPR stand responsible for Non-payment, for example the responsible account payment 159 is 158 (Paying_Account_ID), so the Total_NPR for 159 1

    This is the expected result, any advice appreciated. Thank you
    Level_Label                     Level           Cycle           My_Total_PR     Total_PR     My_Total_NPR     Total_NPR     Paying_Account
    158                               1                0                  2              3          0              0              158
        159                           2                0                  0              0          0              1              158
        160                           2                0                  0              0          0              1              158
    181                               1                0                  0              1          0              0              181
    183                               1                0                  0              1          0              0              183
    24669                             1                0                  0              1          3              3              24669                   
        24671                         2                0                  0              1          0              0              24671
        24670                         2                0                  0              1          1              1              24670
            3385127                   3                0                  0              1          0              0              3385127
    Published by: user11432758 on February 14, 2012 01:00

    Published by: user11432758 on February 14, 2012 07:05

    Hello

    user11432758 wrote:
    Hi here is the statement DDL, thank you

    CREATE TABLE "SYSTEM"."ACCOUNT" ...
    

    Do not create your own objects in the diagram of the SYSTEM or any scheme that comes with the database. Create a separate schema and place your items. You'll have fewer security problems, and the migration to a new database will be easier.

    Here's a way to can get the aggregates you want:

    WITH     got_descendants          AS
    (
         SELECT     CONNECT_BY_ROOT account_id     AS ancestor_id
         ,     paying_account_id
         ,     LEVEL                    AS lvl
         FROM     account
         CONNECT BY NOCYCLE     PRIOR account_id     = parent_account_id
              AND          account_id          != parent_account_id
    )
    SELECT       ancestor_id
    ,       COUNT (CASE WHEN lvl             > 1
                      AND  ancestor_id  = paying_account_id THEN 1 END)     AS my_total_pr
    ,       COUNT (CASE WHEN ancestor_id  = paying_account_id THEN 1 END)     AS total_pr
    ,       COUNT (CASE WHEN lvl             > 1
                      AND  ancestor_id != paying_account_id THEN 1 END)     AS my_total_npr
    ,       COUNT (CASE WHEN ancestor_id != paying_account_id THEN 1 END)     AS total_npr
    FROM       got_descendants
    GROUP BY  ancestor_id
    ;
    

    Output:

    `             MY_         MY_
                TOTAL TOTAL TOTAL TOTAL
    ANCESTOR_ID   _PR   _PR  _NPR  _NPR
    ----------- ----- ----- ----- -----
            158     2     3     0     0
            159     0     0     0     1
            160     0     0     0     1
            181     0     1     0     0
            183     0     1     0     0
          24669     0     1     3     3
          24670     0     1     1     1
          24671     0     1     0     0
        3385217     0     1     0     0
    

    This gives the correct numbers, but how can bring us in an order that reflects the hierarchy, with the columns (for example lvl) that come from the hierarchy?
    A solution would be to make two CONNECT BY queries; a service without START WITH clause (like the one above) who collects the aggregates and the other with a START WITH clause (as your original query), which is in the right order and columns such as level_label and level. We could join result sets and get exactly what we want. I'll leave that as an exercise.

    Here is another way, which gets good results with only one CONNECTION PER request:

    WITH     got_descendants          AS
    (
         SELECT     CONNECT_BY_ROOT account_id     AS ancestor_id
         ,     paying_account_id
         ,     account_id
         ,     LEVEL                    AS lvl
         ,     CONNECT_BY_ISCYCLE          AS cycle
         ,     CASE
                  WHEN  CONNECT_BY_ROOT account_id
                      = CONNECT_BY_ROOT parent_account_id
                  THEN  ROWNUM
              END                    AS r_num
         FROM     account
         CONNECT BY NOCYCLE     PRIOR account_id     = parent_account_id
              AND          account_id          != parent_account_id
         ORDER SIBLINGS BY     account_id     -- Optional
    )
    ,     got_o_num     AS
    (
         SELECT     got_descendants.*
         ,     MIN (r_num) OVER (PARTITION BY  account_id)     AS o_num
         ,     MAX (lvl)   OVER (PARTITION BY  account_id)      AS max_lvl
         FROM     got_descendants
    )
    SELECT       LPAD ( ' '
                , 2 * (MIN (max_lvl) - 1)
                )  || ancestor_id                         AS level_label
    ,       MIN (max_lvl)                                AS "Level"
    ,       MIN (cycle)                                   AS "Cycle"
    ,       COUNT (CASE WHEN lvl             > 1
                      AND  ancestor_id  = paying_account_id THEN 1 END)     AS my_total_pr
    ,       COUNT (CASE WHEN ancestor_id  = paying_account_id THEN 1 END)     AS total_pr
    ,       COUNT (CASE WHEN lvl             > 1
                      AND  ancestor_id != paying_account_id THEN 1 END)     AS my_total_npr
    ,       COUNT (CASE WHEN ancestor_id != paying_account_id THEN 1 END)     AS total_npr
    ,       MIN (paying_account_id)                                    AS paying_account
    FROM       got_o_num
    GROUP BY  ancestor_id
    ORDER BY  MIN (o_num)
    ;
    

    Output:

    `                             MY_         MY_
                                TOTAL TOTAL TOTAL TOTAL  PAYING_
    LEVEL_LABEL     Level Cycle   _PR   _PR  _NPR  _NPR  ACCOUNT
    --------------- ----- ----- ----- ----- ----- ----- --------
    158                 1     0     2     3     0     0      158
      159               2     0     0     0     0     1      158
      160               2     0     0     0     0     1      158
    181                 1     0     0     1     0     0      181
    183                 1     0     0     1     0     0      183
    24669               1     0     0     1     3     3    24669
      24670             2     0     0     1     1     1    24670
        3385217         3     0     0     1     0     0  3385217
      24671             2     0     0     1     0     0    24671
    

    That's exactly what you asked for, except that you have posted the line with level_label =' 24671' before the line with level_label = "24671 '. You may not care about who comes first, but if it's important, explains why these lines should be in descending order of account_id, while "159 and 160" are in ascending order. You will need change the ORDERBY brothers and SŒURS clause accordingly.

  • Hierarchical connect by and start with and joined?

    I have an Employees table and a table of identifiers. The table of identifiers is hierarchical, with parents and children. Each employee has one or more identifiers, but that a unique identifier is considered to be the "primary" or root for each employee identifier. Unfortunately, the employee table can point to one of the children identifier lines and not the root. I need a quick query to reach employees with their most recent ID (root).

    Here's the code to define the problem.
    create table employees (employeeid varchar2(8), fakeNationalID varchar2(9), empname varchar2(30));
    insert into employees (employeeid, fakeNationalID, empname) values (1,'001000001','John Smith');
    insert into employees (employeeid, fakeNationalID, empname) values (2,'002000002','James Jones');
    
    create table realids (realidkey NUMBER, fakeNationalID VARCHAR2(9) not null, 
       realNationalID VARCHAR2(9) UNIQUE, parent_realidkey number);
    insert into realids (realidkey, fakeNationalID, realNationalID, parent_realidkey) values
       (1,'001000001','111111111',3);
    insert into realids (realidkey, fakeNationalID, realNationalID, parent_realidkey) values
       (2,'002000002','222222222',null);
    insert into realids (realidkey, fakeNationalID, realNationalID, parent_realidkey) values
       (3,'003000003','333333333',null);
    commit;   
    
    create or replace function get_parentid (fakeID in VARCHAR2) return varchar2 is
       tempid VARCHAR2(9);
       begin
          select realNationalID into tempid 
             from (
               select realNationalID, fakeNationalID
                  from realids
                  start with fakeNationalID = fakeID
                  connect by nocycle prior parent_realidkey = realidkey
                  order by level desc)
                  where rownum = 1;
          return tempid;
          exception 
             when NO_DATA_FOUND then
                return NULL;
             when others then raise;
        end;
    
        
    select get_parentid('001000001') from dual; -- returns 333333333 because its linked to a parent
    select get_parentid('002000002') from dual; -- returns 222222222 because there is only one child
    select get_parentid('003000003') from dual; -- returns 333333333 because it is the parent
    What I want is to put the parent node above realids for each line of employees...

    It works, but it is NOT very effective:
    select employeeid, get_parentid(fakeNationalID) realid, empname from employees;
    employeeid   realid       empname
    ----------   -----------  ------------
    1            333333333     John Smith
    2            222222222     James Jones
    You can imagine what it would be like with 100K lines or more. It takes about 3 minutes to run.

    It seemed like a good way to do it, but with a sub query.
    select e.employeeid, e.fakenationalid, e.empname, sub.realnationalid
       from employees, 
          (select realidkey, fakenationalid, realnationalid, parent_realidkey
             from realids r
             start with r.fakenationalid = e.fakenationalid
             connect by prior r.parent_realidkey = r.realidkey) sub
    Unfortunately, it produces an invalid identifier on e.fakenationalid (in the beginning with the clause).

    Anyone has any ideas on how to get top most parent node of the realids for each row in the employees table? In real life, there are 6 or more employees tables across multiple remote instances of what children in the realids table and how much to the parents. We always want the highest parent of the page realid. Any help would be appreciated.

    Hello

    Thanks for posting the sample data in a convenient form!
    It is always useful to post your version of Oracle, too, especially when it comes with CONNECT BY queries.

    What follows is what you asked for in Oracle 10:

    WITH     got_roots   AS
    (
         SELECT     CONNECT_BY_ROOT     fakenationalid     AS leaf_id
         ,     realnationalid
         FROM     realids
         WHERE     CONNECT_BY_ISLEAF     = 1
         START WITH      fakenationalid IN ( SELECT  fakenationalid
                                              FROM    employees
                               )
         CONNECT BY     realidKEY     = PRIOR parent_realidkey
    )
    SELECT     e.employeeid
    ,     r.realnationalid
    ,     e.empname
    FROM     employees     e
    JOIN     got_roots     r     ON     r.leaf_id     = e.fakenationalid
    ;
    

    In any query, call a function defined by the user for each line is going to be slow. Fortunately, Oracle now has the built-in functions and operators that can take the place of get_parentid. The CONNECT_BY_ROOT operator, which was introduced in Oracle 10, is the key to the problem. In Oracle 9, you can get the same results using SYS_CONNECT_BY_PATH.

    It is generally faster to CONNECT BY query separately, and then join some other tables you need for results.

    You had a good idea in your last query. The problem was that void and employees were equal tables in the FROM clause, and you cannot establish a correlation between equals. You can only correlate a subquery to its Super application. You could make to this general idea work by changing void in a scalar sub-requete, which can be connected to the employees, but I think it would be much less effective than what I posted above.

  • START WITH and CONNECT BY PRIOR

    Hello

    Database: Oracle 11g

    1.

    SELECT ename, empno, mgr

    WCP

    START WITH empno = 7839

    CONNECT BY PRIOR MGR = EMPNO

    Result set:

    EMPNO, ENAME MGR

    -------- ---------- ----------

    KING 7839

    2.

    SELECT empno.ename, Bishop

    WCP

    START WITH mgr = 7839

    CONNECT BY PRIOR MGR = EMPNO

    Result set:

    EMPNO, ENAME MGR

    -------- ---------- ----------

    7566 JONES 7839

    7698 BLAKE 7839

    7782 CLARK 7839

    KING 7839

    KING 7839

    KING 7839

    My questions are:

    Q1. What is actually happening in the result defines two queries. I'm not able to grasp the difference when I use START WITH empno = 7839 and START WITH mgr =. 7839

    Q2. What is the difference between

    CONNECTION BY MGR PRIOR = EMPNO and

    CONNECT BY PRIOR EMPNO = MGR?

    can someone please help me here?

    Thank you

    Hello

    A CONNECT BY query looks like an operation UNION ALL of the data of different levels, numbered 1, 2, 3 and more.

    Level 1 is filled with the START WITH clause.

    If there are data on level N, then N + 1 level is filled, using the CONNECT BY clause, which generally refers to something on the N level via the PRIOR operator.  Another way to put it is that level N + 1 is filled by a self-join with lines that have already chosen the level N.

    If there is no data on the level of N, the query stops.

    Let's see how this applies to your queries.

    Level being such an important concept in CONNECT BY queries, you might want to see in all your CONNECT BY queries all test and debug the.

    1 query, including the level are:

    SELECT ename, empno, mgr

    LEVEL

    FROM scott.emp

    START WITH empno = 7839

    Empno = mgr PRIOR CONNECTION

    ;

    You will notice that I have re-arranged the CONNECT BY clause.  I find it a little more clear medium.  Of course, it never changes the results just if you say "x = y" or "y = x.

    The results, including the level, are:

    LEVEL OF ARCHBISHOP EMPNO, ENAME

    ---------- ---------- ---------- ----------

    7839 KING 1

    What happened to produce these results?

    First level 1 has been met using the START WITH clause.  Level 1 is identical to the results of

    SELECT ename, empno, mgr

    AS LEVEL 1

    FROM scott.emp

    WHERE empno = 7839 - same as your START WITH clause

    ;

    It happens to be only 1 row in the table scott.emp who met the empno = 7839 condition, and we show a few columns of this line.

    That's all that need the level 1.  Something has been on level 1, so we're trying now to complete level 2, using the CONNECT BY condition.

    Any line that is included in the level 2 meets the empno = mgr PREREQUISITE condition, where the PREVIOUS operator refers to a line of level 1.  In this case, there is only 1 row at level 1, this line gets to have a NULL mgr.  Given that PRIOR mgr is NULL in this case, the condition to connect BY

    EmpNo = mgr BEFORE equals

    EmpNo = NULL and who obviously won't be true for any line, so nothing is added to level 2, and ends the query.

    Now let's look at application 2.  I'll add another column of debugging, called path, which I'll describe later:

    SELECT ename, empno, mgr

    LEVEL

    , SYS_CONNECT_BY_PATH (empno, "/") AS path

    FROM scott.emp

    START WITH mgr = 7839

    CONNECT BY PRIOR Mgr = empno

    LEVEL CONTROL

    path

    ;

    Output:

    EMPNO, ENAME MGR LEVEL PATH

    ---------- ---------- ---------- ---------- ---------------

    7566 7839 1 7566 JONES

    7698 7839 1 7698 BLAKE

    7782 7839 1 7782 CLARK

    7839 KING 2/7566/7839

    7839 KING 2/7698/7839

    7839 KING 2/7782/7839

    Again, we'll study how people got 1 level.  It happens to be 3 scott.emp lines that meet this condition START WITH, so there are 3 lines in the game at level 1.

    Given that the data on the level 1, the test of the query to complete level 2, referring to some PRIOR line on level 1.  Any line that meets the condition to connect BY, with a line any level 1 in the PREVIOUS line, will appear at level 2.

    Let's look at the line at level 1 where ename = 'JONES '.  Are there lines in sccott.emp that met the empno = mgr PREREQUISITE condition, where mgr PREREQUISITE is the column of Archbishop of the line with "JONES"?  Yes, there are one, the line with ename = 'KING', so that the rank is included at level 2.

    Let's look at the line at level 1 where ename = 'BLAKE '.  Are there lines in sccott.emp that met the empno = mgr PREREQUISITE condition, where mgr PREREQUISITE is the column of Archbishop of the line with "BLAKE"?  Yes, there are one, the line with ename = 'KING', so that the rank is included at level 2.

    Let's look at the line at level 1 where ename = 'CLARK '.  Are there lines in sccott.emp that met the empno = mgr PREREQUISITE condition, where mgr PREREQUISITE is the column of Archbishop of the line with 'CLARK '?  Yes, there are one, the line with ename = 'KING', so that the rank is included at level 2.

    There are thus 3 rows at level 2.  They happen to all be on the same line of the table emp; It is correct.  Remember, CONNECT BY is like a UNION ALL (not just a UNION).  It is a UNION of

    lines that are at level 1, because him meets the condition to BEGIN WITH, and

    lines that are at level 2 because puts it CONNECT BY condition regarding the 'JONES', and

    lines that are at level 2, because they meet the condition to connect BY regarding the "BLAKE", and

    lines that are at level 2, because they meet the condition to connect BY regarding the "CLARK".

    SYS_CONNECT_BY_PATH can enlighten us on that.  SYS_CONNECT_BY_PATH (empno, ' / ') shows the empno of each level that caused this line appears in the result set.  It's a delimited list /, where the nth element (i.e. the empno after bar oblique nth) is the empno who found the N level.

    Since there were data at level 2, the quert now trying to complete level 3.

    Is there all the rows in the table that satisfy the CONNECT BY condition (mgr PRIOR = empno) with respect to any line level 2?  No, Bishop is be NULL on all lines of level 2, so no line can satisfy this condition CONNECT BY, no lines are added at level 3, and ends the query.

    I hope that answers the question:

    Q1. What is actually happening in the result defines two queries. I'm not able to grasp the difference when I use START WITH empno = 7839 and START WITH mgr =. 7839

    I'll try to not be so detailed answering

    Q2. What is the difference between

    CONNECTION BY MGR PRIOR = EMPNO and

    CONNECT BY PRIOR EMPNO = MGR?

    These 2 CONNECT BY conditions are different where you put the PRIOR operator.  The operator PRIOR to switching as it change the direction, upward or downward, which move you through the tree you get from level to level.

    Bishop PRÉALABLE = empno means the employee on level N + 1 will be the same as the Manager of level N.  This means that higher level numbers will be the most senior people in the hierarchy.  This is called a query from the bottom up.  (Both of the queries that you have posted this same CONNECT BY exact state; both are requests from bottom to top).

    Mgr = empno PREREQUISITE or equivalent

    PRIOR empno = mgr means exactly the opposite.  When you move from level N to level N + 1 in the query, you will move to an older person, to a junior position in the hierarchy.  This is called a query from top to bottom.  The employee level N will be the Manager of wover is a level N + 1.

  • Start - and connect SQL to the lowest level in the tree or the hierarchy

    Hello

    In a tree structure as shown below how can I get all the child (tree) level lowest records as a - E, H, G, and D.
    A a B, C, D to level 2
    B E and F at level 3, and C G at level 3
    F a H level 4

    A
    | l | l | l
    B C D
    | l | l | l
    E F G
    | l
    H

    I have used start with and coonect by to give all levels of the tree as follows: -.
    SELECT task_id, parent_task_id, top_task_id, level
    OF pa_tasks
    WHERE project =: p
    START WITH parent_task_id IS NULL
    CONNECT BY PRIOR task_id = parent_task_id

    Thank you

    Published by: user10648285 on October 17, 2011 23:42

    Published by: user10648285 on October 17, 2011 23:42

    Published by: user10648285 on October 17, 2011 23:42

    Published by: user10648285 on October 17, 2011 23:43

    Oracle a [url http://download.oracle.com/docs/cd/E11882_01/server.112/e26088/pseudocolumns001.htm#i1009313] nickname for hierarchical queries:

    SELECT task_id,parent_task_id, top_task_id,level
    FROM pa_tasks
    WHERE project_id = :bind_variable
    and connect_by_isleaf = 1
    START WITH parent_task_id IS NULL
    CONNECT BY PRIOR task_id = parent_task_id
    
  • Understanding "CONNECT BY" and "START WITH".

    OK, I'm trying to update the rows with values determined by lines joined in a recursive relationship of unknown depth. I am told that "CONNECT BY" and "START WITH" can be useful in this, but I don't see how to get the value I'm looking for.

    In my case, there are 3 values in my table.
    ID
    ID of the parent
    Invoice

    On some lines, the Bill is null. For records, you get the ID of the invoice by searching for the invoice of the parent folder. I'm trying to update the table so that all THE rows in the table have an ID of invoice.

    Here is an example of table and the lines.
    CREATE TABLE DISTRIBUTION (
    ID            INT,
    INV_NUM       INT,
    PARENT_ID     INT
    )
    
    INSERT INTO DISTRIBUTION 1, 111, NULL;
    INSERT INTO DISTRIBUTION 2, 112, NULL;
    INSERT INTO DISTRIBUTION 3, NULL, 2;
    INSERT INTO DISTRIBUTION 4, 113, NULL;
    INSERT INTO DISTRIBUTION 5, NULL, 4;
    INSERT INTO DISTRIBUTION 6, NULL, 5;
    INSERT INTO DISTRIBUTION 7, NULL, 6;
    What I would do is update the inv_num column in the table so that a select statement * would look like this...
    ID        INV_NUM    PARENT_ID
    -----     -------------     ---------------
    1            111           null
    2            112           null
    3            112              2
    4            113           null
    5            113              4
    6            113              5
    7            113              6
    You can provide any help would be greatly appreciated.

    Hello

    Thank you post the CREATE TABLE and INSERT instructions, but please make sure that they work.
    None of the INSERT statements; I think you meant something like the statements shown after the query.

    Here's a way to get the desired results:

    UPDATE  distribution     m
    SET     inv_num = ( SELECT  inv_num
                  FROM    distribution
                  WHERE   CONNECT_BY_ISLEAF     = 1
                  START WITH     id          = m.id
                  CONNECT BY     id          = PRIOR parent_id
                           AND     PRIOR inv_num     IS NULL
                   )
    WHERE   inv_num       IS NULL
    ;
    

    This statement is Bottom-Up of subqueries, where we START WITH the lines that need to update, and process to the top of the tree, until you get to an ancestor who was an inv_num.
    In your sample data, only the roots (the lines that have no parents) have inv_num. In this case, it might be a little easier (but only a little) to make a request from top to bottom , where we START WITH the roots and low process in the tree to find their subordinates.
    If we add some data examples where a nonroot has inv_num:

    INSERT INTO DISTRIBUTION (id, inv_num, parent_id) VALUES ( 91, 910,   1);
    INSERT INTO DISTRIBUTION (id, inv_num, parent_id) VALUES ( 92, NULL, 91);
    

    What results would you like?
    Using the UPDATE statement above, id = 92 would get his inv_nuym of the closest ancestor (in the case of thios, parent) who had an inv_num:

    .       ID    INV_NUM  PARENT_ID
    ---------- ---------- ----------
             1        111
            91        910          1
            92        910         91
             2        112
             3        112          2
             4        113
             5        113          4
             6        113          5
             7        113          6
    

    Either the row with id = 92 gets inv_num = 910, no 111.

Maybe you are looking for

  • How can I fix missing InetClnt.dll

    My gives computer I an error message when I turn on missing InetClnt.dll How can fix this?

  • Windows XP Professional do not start; Strange message in German

    As a result of my monitor suddenly change color, I tried to do a system restore. When my computer restarts, it displays a message in German (?): «Der bootsektor dieser floppy wurde neu standing.» Use sie den BACK instruction SYS um sharp floppy boata

  • BlackBerry Q10 Q10 takes only 60 days emails?

    Is it possible to extend the waiting period? Anything under account settings.

  • Default values for LOV cascading

    Hello. I have 2 list select say fields A and B. 2 values and a B has 10 values. If I select 1st value has, the value must be filled in B, but the user should be able to change if he wants to in IE, when the drop-down list is selected in the B 10 valu

  • How to create a Collection validator using accessor?

    I'm learning to ADFI created a validator of collection on a parent entity object (the object of child entity and the association are created equally), but when I tried to choose a list accessor appears emptyWhere can I get this accessor?Note: I'm con