How to query a hierarchical structure (Director and employee)

Hi all
I use the Oracle 10 g R2 database.
Suppose I have this structure
EMP_ID               EMP_NAME          MANAGER_ID
1                    KING               
2                    STEVE               1
3                    FRANK               2
What I want, that is when I get any EMP_ID, I want to get all the Manager of his first and the last record is the employee in the leaf of the hierarchy in the query.

For example, when I ask EMP_ID = 2, I want to get this result
EMP_ID               EMP_NAME          MANAGER_ID
1                    KING               
2                    STEVE               1
and when I search EMP_ID = 3, I want to get this result:
EMP_ID               EMP_NAME          MANAGER_ID
1                    KING               
2                    STEVE               1
3                    FRANK               2
How to write this query?
with xx as
(
select 1 eid, 'KING' emp_name, NULL mid from dual UNION ALL
select 2 eid, 'STEVE' emp_name, 1 mid from dual UNION ALL
select 3 eid, 'FRANK' emp_name, 2 mid from dual
)
select *
        from xx
    start with eid = 2
    connect by eid = PRIOR mid
order by eid;

Output:

1     KING
2     STEVE     1

With emp_id = 3

with xx as
(
select 1 eid, 'KING' emp_name, NULL mid from dual UNION ALL
select 2 eid, 'STEVE' emp_name, 1 mid from dual UNION ALL
select 3 eid, 'FRANK' emp_name, 2 mid from dual
)
select *
        from xx
    start with eid = 3
    connect by eid = PRIOR mid
order by eid;

Output:

1     KING
2     STEVE     1
3     FRANK     2

Tags: Database

Similar Questions

  • Hierarchical query, differentiate between the leafs and nodes?

    Hello

    I started coding a small program PL/SQL (not finished) with a hierarchical query:
    DECLARE
    
    CURSOR cur IS
    select 
      op_id||' '||op_descript as description, level
    from operations
    connect by prior op_id = op_parent_op_id
    start with op_id = 0;
    
    BEGIN
    
    HTP.prn('<ul id="arbre2" class="filetree">');
      for c in cur loop
        HTP.prn('<li><span class="folder">'||c.description||'</span></li>');
      end loop;
    
      HTP.prn('</ul>');
    END;
    This program must return a hierarchical HTML code like this (he does not at the moment):
    <ul id="arbre" class="filetree">
     <li><span class="folder">Folder 1</span>
      <ul>
       <li><span class="file">Item 1.1</span></li>
      </ul>
     </li>
     <li><span class="folder">Folder 2</span>
      <ul>
       <li><span class="folder">Subfolder 2.1</span>
        <ul>
         <li><span class="file">File 2.1.1</span></li>
         <li><span class="file">File 2.1.2</span></li>
        </ul>
       </li>
       <li><span class="file">File 2.2</span></li>
      </ul>
     </li>
     <li class="closed"><span class="folder">Folder 3 (closed at start)</span>
      <ul>
       <li><span class="file">File 3.1</span></li>
      </ul>
     </li>
     <li><span class="file">File 4</span></li>
    </ul>
    then jQuery will make a tree.

    But I don't know how to differentiate leafs and nodes in the request, to allow me to specify a class = 'file' or class = 'file '.

    Does anyone have a solution?

    A more general question might be: how to generate a hierarchical HTML code exactly as it is above my table operations (op_id, op_parent_op_id, descript).

    Thank you.

    Yann.

    Discover the CONNECT_BY_ISLEAF pseudo-column. Returns 1 if it is a leaf and zero otherwise.

    HTH!

  • How to convert the hierarchical query of SQL Server (CTE) to Oracle?

    How to convert the hierarchical query of SQL Server (CTE) to Oracle?

    WITH cte (col1, col2) AS
    (
    SELECT col1, col2
    FROM dbo. [tb1]
    WHERE col1 = 12
    UNION ALL
    SELECT c.col1, c.col2
    FROM dbo. [tb1] AS c INNER JOIN cte AS p ON c.col2 = p.col1
    )
    DELETE one
    FROM dbo. [tb1] AS an INNER JOIN b cte
    ON a.col1 = b.col1

    Hello
    Something like this maybe:

    DELETE FROM dbo.tb1 a
     WHERE EXISTS (
      SELECT 1
        FROM dbo.tb1 b
      WHERE a.co11 = b.col1
          AND a.col2 = b.col2
       START WITH b.col1 = 12
      CONNECT BY b.col2 = PRIOR b.col1)
    

    Although you need to do here is to check that CONNECT it BY SELECT, returns records you wait first, then the DELETION should work too.

  • Can we make several Off features in a collection of panels and how the query-off based on the example?

    Mr President.

    Can we make several Off features in a collection of panels and how the query-off based on the example?

    Concerning

    Once again, no jdev version?

    It must be really hard to remember ehich version you are working.

    Would have given a quick glance in the docs

    featuresOff java.util.Set Yes a list separated by spaces of the features by default to disable to the panelCollection. Values supported are

    That is the answer to a message.

    The second answer is that qbe is filtering tables. If you fund the table without filter you have not the qbe.

    Timo

  • How can I disable hierarchical keywording in LR 5?  The preference of the interface for the AutoComplete is turned off and I still get California &gt; United States &gt; country.  I want to just Caliofrnia.

    How can I disable hierarchical keywords in Lightroom?  The preference of the Interface for full Auto is already disabled, but I still get California > United States > North America when all I need is the California.

    You must be signed in order to respond to messages.

    One of the reasons why you can see the hierarchical format for the key words are you have the word 'California' duplicate key in your keyword list.

    Lightroom display these files directly with.< parent-keywords"="" appended="" to="" the="">

    IE California< state="">< country ="" and="" california="">< united="">

    If you re - keyword photos so that they use only one version and then delete it key word duplicate of your keyword list and then she displays just "California".

    Bruce

  • How to create a report that will show us the hierarchical structure

    Hi all

    I use studio financial reporting for reports.
    I have a planning application. And I used areas such as the entity Dimension.

    Now, I am creating a report of users to see my hierarchy of dimension entity.
    Something like areas
    East
    West
    North
    South

    I'm able to generate the report, but the hierarchy of areas does not appear...

    Can someone advice if there is an option in the preparation of financial reports to make more visible the hierarchical structure by adding a correct indentation between the parent and child?...

    And Yes, I used a prompt for the entity in the report...

    Thank you

    You could add indentation around the lines of formatting.

    1. Select the line
    2. Select Format
    3. click on the tab of allignment
    4. set a number for the indentation.

    Good luck!

  • How can I place a structure on another structure while keeping in - and the son intact?

    I would like to cover 2 Structure Structure 1, while all sons- and automatically adjusts and crosses the border of the Structure 2. Is it possible - or what I need to manually remove all the wires, then place the structure 1 inside the Structure 2 and finally thread manually all the wires yet :-(?

    Hello!

    It works for me, LV2011. You must select forloop in your control panel, and then draw it around the forloop you've already got there. Impossible to draw two forloops and then just move on the other. It will not work with the son.

  • How to query the total number of columns and lines filled with data?

    How to get the number of rows and columns in Exel file data using Excel report?

    Since you have posted this question in the forum of LabWindows/CVI, I guess you want to know how to do with CVI.

    You need to know how to open and activate the Excel data file.

    Depending on the function returns the total number of columns and lines col_count row_count, respectively.

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

    int CountColumnsAndRows (void)
    {
    Error HRESULT = 0;
    CAObjHandle rangeCurrentRegionHandle = 0;
    CAObjHandle rangeColumnsHandle = 0;
    CAObjHandle rangeRowsHandle = 0;
      
    unsigned long col_count = 0, row_count = 0;
      
    Must use the 'A1' property and CruuentRegion count the total of columns and lines, including the drafts!
      
    error = CA_VariantSetCString (& MyCellRangeV, 'A1');
      
    error = Excel_WorksheetRange (ExcelWorksheetHandle, NULL, MyCellRangeV, CA_DEFAULT_VAL, & ExcelRangeHandle);
    If (error<0) goto="">
      
    error = Excel_GetProperty (ExcelRangeHandle, & ErrorInfo, Excel_RangeCurrentRegion, CAVT_OBJHANDLE, & rangeCurrentRegionHandle);
    If (error<0)  goto="" error="">
      
    error = Excel_GetProperty (rangeCurrentRegionHandle, & ErrorInfo, Excel_RangeColumns, CAVT_OBJHANDLE, & rangeColumnsHandle);
    If (error<0)  goto="" error="">
      
    error = Excel_GetProperty (rangeColumnsHandle, & ErrorInfo, Excel_RangeCount, CAVT_LONG, & col_count);
    If (error<0) goto="">
      
    error = Excel_GetProperty (rangeCurrentRegionHandle, & ErrorInfo, Excel_RangeRows, CAVT_OBJHANDLE, & rangeRowsHandle);
    If (error<0)  goto="" error="">
      
    error = Excel_GetProperty (rangeRowsHandle, & ErrorInfo, Excel_RangeCount, CAVT_LONG, & row_count);
    If (error<0) goto="">

    Error:

    CA_VariantClear (& MyCellRangeV);
    CA_VariantClear (& MyVariant);
    ClearObjHandle (& ExcelRangeHandle);
    ClearObjHandle (& rangeCurrentRegionHandle);
    ClearObjHandle (& rangeColumnsHandle);
    ClearObjHandle (& rangeRowsHandle);
      
     
    If (error<>
    ReportAppAutomationError (error);
      
    error return;
    }

  • A query with workingdays by month and per period

    Can someone help me on how to build a SQL query that is difficult?

    I work with SQL Oracle. It is intended to be calculated over a certain period, to find the working days of each month for each person.

    I have a request to work to calculate the number of days 1 month less holidays

    SELECT count (*) NUM_WORK_DAYS
    De)
    Select to_date (January 1, 2010 ", 'dd-mm-yyyy') + ROWNUM-1 day
    Of object
    Where ROWNUM < to_number (to_char (last_day (January 1, 2010 '), JJ ')) + 1).
    Where to_number (to_char (day, 'd.')) between 1 and 5
    And not exists (select NULL
    Holiday
    Where Holiday.hol = day)

    There is a datetable with the following structure where I can get the periods:
    DATES
    YEAR | MONTH | WEEK | SD
    2010 | 201002 | 201006 | 02/09/2010
    All the required month are present
    It is expected that the user gives a start and specify an end time.

    I have a table of workingdays per person named
    CALENDAR
    CAL | MY | MAR | SEA | GAME | FRI | SAM | SUN
    Nobody | THERE | THERE | N | THERE | THERE | N | N

    And an array of holidays
    HOLIDAY
    CAL | HOL
    Nobody | 01/01/2010

    How can I combine the query for the business days and create a query that returns the number of workingdays by month for many people for several months? I will ask the user to give a start point and an end of period

    I am aware that I ask a lot of your time, but I can't imagine the solution myself. Thanks in advance

    GR,
    Els

    You can change the query in this way:

    with period as (
    select DATE '&start_day' start_date, DATE '&end_day' end_date
      from dual),
    days as (
    select start_date+level-1 day
      from dual,period
    connect by level <= end_date-start_date+1),
    mycal as (
    select person, 'monday' day, mon works from calendar union all
    select person, 'tuesday' day, tue from calendar union all
    select person, 'wednesday' day, wed from calendar union all
    select person, 'thursday' day, thu from calendar union all
    select person, 'friday' day, fri from calendar union all
    select person, 'saturday' day, sat from calendar union all
    select person, 'sunday' day, sun from calendar
    )
    select person, to_char(d.day,'yyyymm') month, count(0)
      from mycal c, days d
     where c.day = trim(to_char(d.day,'day'))
       and c.works='Y'
       and not exists (select 1 from holiday h where h.person=c.person and h.hol=d.day)
    group by person, to_char(d.day,'yyyymm');
    

    Max
    http://oracleitalia.WordPress.com

  • 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.

  • How to detect the window closing event and to do some tasks before leaving

    Hello

    Someone knows how to detect the window closing event and to do some tasks before leaving?

    Sridhar

    Structure of the event allows to detect the window closing event. In the structure of the event,.

    Select this VI-> close round table for this task. See attached picture.

  • I use Director and I got about 100 picture in my project and I want to bring up more time on the screen when reading it.

    I use Director and I got about 100 picture in my project and I want to bring up more time on the screen when reading it. I know you can do induvdually but I was wondering if there was a way to select all and then make the longer time for each of them. Help, please!

    original title: NEED HELP Please REPLY as soon as POSSIBLE. Windows movie maker question

    Hello

    My friend John Papa - MVP - is the expert on Windows Movie Maker.

    PapaJohn.org
    http://Papajohn.org/

    PapaJohn - online tutorials
    http://www.Papajohn.org/mm2-online-tutorials.html

    Windows Movie Maker Tutorials - check the sounds of the addition in the left menu and others on the
    main screen.
    http://www.windowsmoviemakers.NET/tutorials/

    Windows Live Movie Maker help & how-to and Forums are good sources of information:

    Windows Essential - Movie Maker help
    http://Windows.Microsoft.com/en-us/Windows-Live/Essentials-Help-Center?T1=T3

    Answers - Windows Essentials - Microsoft Windows Movie Maker Forums
    http://answers.Microsoft.com/en-us/windowslive/Forum/MovieMaker?tab=threads
    ====================

    These might help:

    Getting started with Windows Movie Maker

    Import video, photos and audio on Windows Movie Maker

    Import video from a videotape

    Get a movie in Windows Movie Maker

    Make a movie quickly in Windows Movie Maker (AutoMovie)

    Publish a movie in Windows Movie Maker

    I hope this helps.

    Rob Brown - Microsoft MVP<- profile="" -="" windows="" expert="" -="" consumer="" :="" bicycle=""><- mark="" twain="" said="" it="">

  • How to download Windows 7 COA diskless and install on a virtual machine?

    How to download Windows 7 COA diskless and install it in the Virtual Machine?
    Thank you
    Emmanuel

    Hi EmmanuelBoutboul1,

    The question you posted would be better suited in the TechNet Forums. I would recommend posting your query in the TechNet Forums.

    http://social.technet.Microsoft.com/forums/Windows/en-us/home?category=w7itpro&filter=AllTypes&sort=lastpostdesc

    It will be useful.

  • Duplicate files: I have a large number of directories and files dublicate in "C:\Documents and Settings".

    I have a large number of dublicate files and directories in 'C:\Documents and Settings\Jim\' and 'C:\Users\Jim\' after the upgrade of Windows Vistat Ultimate 64 bit to Windows 7 Professional 64 bit. Why?

    The documents are really in the second folder, Documents and Settings is
    a junction point.
     
    In Vista and Windows 7, "Documents and Settings" is not a folder.
    Vista/Win7 uses a different file structure than XP/don't. Those who don't know
    the names of folders you can be used for, such as "My Documents", "Documents &.
    Settings', etc. are not folders in Vista/Win7. They are the points of junction,
    and are used for legacy programs that have been written to use the XP file
    structure.
    They will redirect the programs to use the Vista/Win7 equivalents records.
    If you keep hidden protected operating system files, you will not see them.
     
    In Vista/Win7...
    The documents & settings-> \Users
    My Documents-> \Users\youraccount\Documents
    My music-> \Users\youraccount\Music
    Application-> \Users\youraccount\AppData data
    etc.
     
     
     
    --
    Dave N.
    MS - MVP (Mail)
    Windows 7 Ultimate
    http://download.live.com/wlmail
     
     
     
    "JFH36" wrote in message news: 47b4c064-b6eb-4551-b2a4-4b2e42a45f75...
    > I have a large number of directories and files dublicate in 'C:\Documents '.
    ' > and Settings\Jim\ ' and 'C:\Users\Jim\' after the upgrade to Windows
    > Vistat Ultimate 64 bit to Windows 7 Professional 64 bit. Why?
    >
     

    Windows 7 Ultimate 64

  • How can I remove the administrator account and perform a factory restore?

    Original title: how to delete the profile directors and password if you've blocked out of it and that you don't have a cd player for upgrade to windows 8 when you buy the software

    I recently bought my computer from a friend of mine and he forgot his password to the administrator account and I can't do anything as change download settings nothing I want to just remove it at the factory but can't do not know how and I do not think that it won't let me

    You perform a factory restore to make the machine 'as new '. Consult the manufacturer's web page for detailed instructions.

Maybe you are looking for