Self join question

Hi everyone,
In the below employee table, I require the foll output, if the ID and mgr_id of employee table are same then only that output needs to be displayed, so the output should be only
ID Data mgr_ID
1 sss 1
If the reference of 1 is there in mgr_ID for ID 2, then it should not be displayed, only the refernce of 1 to itself or 2 to itself should be displayed.
Employee table:
ID data mgr_ID
1 sss 1
2 aaa 1
3 bbb 2
4 ccc 3
How should the query be written ?

Must have missed your point. Based on your required output I thought just
select *
  from emp
where id = mgr_idRegards
Etbin

Similar Messages

  • SQL query -- self-join question?

    SQL> l
    1* select originator,destination,oaddress,daddress from (select * from activity where rownum<=3)
    SQL> /
    10099 10004 16196344392 16199375530
    10064 10002 18454644069 18456563415
    10065 10006 18302650166 16416609306
    looking at the above query, i am just performing a simple select from one of my tables. Now i require the carriername for both originator and destination columns, and the names for these are found on another table carrier.
    so, i am re-write the above query as: (join with carrier table)
    SQL>
    SQL> select originator,destination,oaddress,daddress,carriername from (select * from activity,carrier where originator=carrier_code and rownum<=3);
    10006 10099 19182772772 19189553062 USA1
    10004 10311 15096701636 15096692171 USA2
    10000 10003 15125898141 15122930569 USA3
    Now, i got the carrier name for my originator, how would i find the carriername for my destination also (in the same query). One way of doing it is joining the carrier table twice, but is there any other better approach.
    Hope i am clear, any help will be greatly appreciated. Thanks.

    select
             A.originator, A.destination, A.oaddress, A.daddress
           , B.carrier_name name_originator
           , C.carrier_name name_destination
       from
             activity  A
            ,carrier  B
            ,carrier  C
      where
             A.originator  = B.carrier_code
         and A.destination = C.carrier_code

  • Tuning question. Self join vs Analytical function

    Hi all,
    I am a bit confused about this query cost.
    So I have this query. Now follow the original one (after rewritten by me):
    SELECT /*+ parallel (d 8) parallel(h 8) parallel(c 8) */
         DISTINCT
    d.customer_node_id AS root_customer_node_id,
    d.customer_node_id AS customer_node_id,
    nvl(h.account_id,c.account_id) AS account_id,
    nvl(h.account_name,c.account_name) AS account_name,
    d.service_id AS service_id,
    nvl((SELECT /*+ parallel(x 8) */ max(x.service_name) FROM delta_service_history x
    WHERE x.service_id=d.service_id AND v_upperbound_upd_dt BETWEEN x.effective_start_date AND x.effective_end_date GROUP BY x.service_id),d.service_name) AS service_name
    FROM
    delta_service_history d,
    delta_account c,
    stg_hierarchy h
    WHERE
    d.customer_node_id=c.customer_node_id(+) AND
    d.customer_node_id=h.customer_node_id(+)
    ......the new one (I decided to use analitycal function to calculate max(service_name) for each service_id instead of self join done for "delta_service_history" )
    I thought that self join was very heavy....
    Anyway, my two questions are:
    1. why the second one is heavier than the first. I reduce the number of join.....
    2. how can be rewritten the first one query? In particular way I don't like that self join..... :)
    Select Distinct
                   root_customer_node_id,
                   customer_node_id,
                   account_id,
                   account_name,
                   service_id,
    service_name
                   From
                                  SELECT /*+ parallel (d 8) parallel(h 8) parallel(c 8) */
                                  d.customer_node_id AS root_customer_node_id,
                                  d.customer_node_id AS customer_node_id,
                                  nvl(h.account_id,c.account_id) AS account_id,
                                  nvl(h.account_name,c.account_name) AS account_name,
                                  d.service_id AS service_id,
                                  d.service_name,
                                  row_number() over (partition by d.service_id order by d.service_name desc) r1
                             FROM
                                  delta_service_history d,
                                  delta_account c,
                                  stg_hierarchy_new h
                             WHERE
                                  d.customer_node_id=c.customer_node_id(+) AND
                                  d.customer_node_id=h.customer_node_id(+) AND
                                  v_upperbound_upd_dt BETWEEN d.effective_start_date AND d.effective_end_date
                             )a
                        Where a.r1 = 1
    Thank you all.

    I Post query plan.
    First one query (the original):
    Plan
    MERGE STATEMENT ALL_ROWSCost: 2.691.669 Bytes: 784.141.119.324 Cardinality: 1.754.230.692                                                                            
         27 MERGE STGADMIN.STG_HIERARCHY                                                                       
              26 PX COORDINATOR                                                                  
                   25 PX SEND QC (RANDOM) PARALLEL_TO_SERIAL SYS.:TQ10005 :Q1005Cost: 2.691.669 Bytes: 475.396.517.532 Cardinality: 1.754.230.692                                                             
                        24 VIEW PARALLEL_COMBINED_WITH_PARENT STGADMIN. :Q1005                                                       
                             23 HASH JOIN RIGHT OUTER BUFFERED PARALLEL_COMBINED_WITH_PARENT :Q1005Cost: 2.691.669 Bytes: 475.396.517.532 Cardinality: 1.754.230.692                                                   
                                  4 BUFFER SORT PARALLEL_COMBINED_WITH_CHILD :Q1005                                             
                                       3 PX RECEIVE PARALLEL_COMBINED_WITH_PARENT :Q1005Cost: 20,828 Bytes: 860.278.720 Cardinality: 15.362.120                                         
                                            2 PX SEND HASH PARALLEL_FROM_SERIAL SYS.:TQ10000 Cost: 20,828 Bytes: 860.278.720 Cardinality: 15.362.120                                    
                                                 1 TABLE ACCESS FULL TABLE STGADMIN.STG_HIERARCHY Cost: 20,828 Bytes: 860.278.720 Cardinality: 15.362.120                               
                                  22 PX RECEIVE PARALLEL_COMBINED_WITH_PARENT :Q1005Cost: 2.669.426 Bytes: 376.698.378.630 Cardinality: 1.752.085.482                                              
                                       21 PX SEND HASH PARALLEL_TO_PARALLEL SYS.:TQ10004 :Q1004Cost: 2.669.426 Bytes: 376.698.378.630 Cardinality: 1.752.085.482                                         
                                            20 VIEW PARALLEL_COMBINED_WITH_PARENT STGADMIN. :Q1004Cost: 2.669.426 Bytes: 376.698.378.630 Cardinality: 1.752.085.482                                    
                                                 19 SORT UNIQUE PARALLEL_COMBINED_WITH_PARENT :Q1004Cost: 2.669.426 Bytes: 127.902.240.186 Cardinality: 1.752.085.482                               
                                                      18 HASH JOIN OUTER PARALLEL_COMBINED_WITH_PARENT :Q1004Cost: 35,386 Bytes: 127.902.240.186 Cardinality: 1.752.085.482                          
                                                           13 HASH JOIN OUTER PARALLEL_COMBINED_WITH_PARENT :Q1004Cost: 4,86 Bytes: 647.395.154 Cardinality: 13.212.146                     
                                                                8 PX RECEIVE PARALLEL_COMBINED_WITH_PARENT :Q1004Cost: 1,961 Bytes: 158.611.600 Cardinality: 6.344.464                
                                                                     7 PX SEND HASH PARALLEL_TO_PARALLEL SYS.:TQ10001 :Q1001Cost: 1,961 Bytes: 158.611.600 Cardinality: 6.344.464           
                                                                          6 PX BLOCK ITERATOR PARALLEL_COMBINED_WITH_CHILD :Q1001Cost: 1,961 Bytes: 158.611.600 Cardinality: 6.344.464      
                                                                               5 TABLE ACCESS FULL TABLE PARALLEL_COMBINED_WITH_PARENT STGADMIN.DELTA_SERVICE_HISTORY :Q1001Cost: 1,961 Bytes: 158.611.600 Cardinality: 6.344.464
                                                                12 PX RECEIVE PARALLEL_COMBINED_WITH_PARENT :Q1004Cost: 2,879 Bytes: 368.690.880 Cardinality: 15.362.120                
                                                                     11 PX SEND HASH PARALLEL_TO_PARALLEL SYS.:TQ10002 :Q1002Cost: 2,879 Bytes: 368.690.880 Cardinality: 15.362.120           
                                                                          10 PX BLOCK ITERATOR PARALLEL_COMBINED_WITH_CHILD :Q1002Cost: 2,879 Bytes: 368.690.880 Cardinality: 15.362.120      
                                                                               9 TABLE ACCESS FULL TABLE PARALLEL_COMBINED_WITH_PARENT STGADMIN.STG_HIERARCHY :Q1002Cost: 2,879 Bytes: 368.690.880 Cardinality: 15.362.120
                                                           17 PX RECEIVE PARALLEL_COMBINED_WITH_PARENT :Q1004Cost: 28,982 Bytes: 5.838.854.928 Cardinality: 243.285.622                     
                                                                16 PX SEND HASH PARALLEL_TO_PARALLEL SYS.:TQ10003 :Q1003Cost: 28,982 Bytes: 5.838.854.928 Cardinality: 243.285.622                
                                                                     15 PX BLOCK ITERATOR PARALLEL_COMBINED_WITH_CHILD :Q1003Cost: 28,982 Bytes: 5.838.854.928 Cardinality: 243.285.622           
                                                                          14 TABLE ACCESS FULL TABLE PARALLEL_COMBINED_WITH_PARENT STGADMIN.DELTA_ACCOUNT :Q1003Cost: 28,982 Bytes: 5.838.854.928 Cardinality: 243.285.622      
    ...second query
    Plan
    MERGE STATEMENT ALL_ROWSCost: 3.521.711 Bytes: 291.687.979.305 Cardinality: 652.545.815                                                                                                     
         32 MERGE STGADMIN.STG_HIERARCHY                                                                                                
              31 PX COORDINATOR                                                                                           
                   30 PX SEND QC (RANDOM) PARALLEL_TO_SERIAL SYS.:TQ10006 :Q1006Cost: 3.521.711 Bytes: 176.839.915.865 Cardinality: 652.545.815                                                                                      
                        29 VIEW PARALLEL_COMBINED_WITH_PARENT STGADMIN. :Q1006                                                                                
                             28 HASH JOIN RIGHT OUTER BUFFERED PARALLEL_COMBINED_WITH_PARENT :Q1006Cost: 3.521.711 Bytes: 176.839.915.865 Cardinality: 652.545.815                                                                            
                                  4 BUFFER SORT PARALLEL_COMBINED_WITH_CHILD :Q1006                                                                      
                                       3 PX RECEIVE PARALLEL_COMBINED_WITH_PARENT :Q1006Cost: 20,828 Bytes: 860.278.720 Cardinality: 15.362.120                                                                  
                                            2 PX SEND HASH PARALLEL_FROM_SERIAL SYS.:TQ10000 Cost: 20,828 Bytes: 860.278.720 Cardinality: 15.362.120                                                             
                                                 1 TABLE ACCESS FULL TABLE STGADMIN.STG_HIERARCHY Cost: 20,828 Bytes: 860.278.720 Cardinality: 15.362.120                                                        
                                  27 PX RECEIVE PARALLEL_COMBINED_WITH_PARENT :Q1006Cost: 3.500.345 Bytes: 140.125.783.665 Cardinality: 651.747.831                                                                       
                                       26 PX SEND HASH PARALLEL_TO_PARALLEL SYS.:TQ10005 :Q1005Cost: 3.500.345 Bytes: 140.125.783.665 Cardinality: 651.747.831                                                                  
                                            25 VIEW PARALLEL_COMBINED_WITH_PARENT STGADMIN. :Q1005Cost: 3.500.345 Bytes: 140.125.783.665 Cardinality: 651.747.831                                                             
                                                 24 SORT UNIQUE PARALLEL_COMBINED_WITH_PARENT :Q1005Cost: 3.500.345 Bytes: 121.225.096.566 Cardinality: 651.747.831                                                        
                                                      23 VIEW PARALLEL_COMBINED_WITH_PARENT STGADMIN. :Q1005Cost: 1.195.554 Bytes: 121.225.096.566 Cardinality: 651.747.831                                                   
                                                           22 WINDOW SORT PUSHED RANK PARALLEL_COMBINED_WITH_PARENT :Q1005Cost: 1.195.554 Bytes: 58.005.556.959 Cardinality: 651.747.831                                              
                                                                21 PX RECEIVE PARALLEL_COMBINED_WITH_PARENT :Q1005Cost: 1.195.554 Bytes: 58.005.556.959 Cardinality: 651.747.831                                         
                                                                     20 PX SEND HASH PARALLEL_TO_PARALLEL SYS.:TQ10004 :Q1004Cost: 1.195.554 Bytes: 58.005.556.959 Cardinality: 651.747.831                                    
                                                                          19 WINDOW CHILD PUSHED RANK PARALLEL_COMBINED_WITH_PARENT :Q1004Cost: 1.195.554 Bytes: 58.005.556.959 Cardinality: 651.747.831                               
                                                                               18 HASH JOIN OUTER PARALLEL_COMBINED_WITH_PARENT :Q1004Cost: 34,402 Bytes: 58.005.556.959 Cardinality: 651.747.831                          
                                                                                    13 HASH JOIN OUTER PARALLEL_COMBINED_WITH_PARENT :Q1004Cost: 4,859 Bytes: 319.455.955 Cardinality: 4.914.707                     
                                                                                         8 PX RECEIVE PARALLEL_COMBINED_WITH_PARENT :Q1004Cost: 1,963 Bytes: 152.576.580 Cardinality: 3.721.380                
                                                                                              7 PX SEND HASH PARALLEL_TO_PARALLEL SYS.:TQ10001 :Q1001Cost: 1,963 Bytes: 152.576.580 Cardinality: 3.721.380           
                                                                                                   6 PX BLOCK ITERATOR PARALLEL_COMBINED_WITH_CHILD :Q1001Cost: 1,963 Bytes: 152.576.580 Cardinality: 3.721.380      
                                                                                                        5 TABLE ACCESS FULL TABLE PARALLEL_COMBINED_WITH_PARENT STGADMIN.DELTA_SERVICE_HISTORY :Q1001Cost: 1,963 Bytes: 152.576.580 Cardinality: 3.721.380
                                                                                         12 PX RECEIVE PARALLEL_COMBINED_WITH_PARENT :Q1004Cost: 2,879 Bytes: 368.690.880 Cardinality: 15.362.120                
                                                                                              11 PX SEND HASH PARALLEL_TO_PARALLEL SYS.:TQ10002 :Q1002Cost: 2,879 Bytes: 368.690.880 Cardinality: 15.362.120           
                                                                                                   10 PX BLOCK ITERATOR PARALLEL_COMBINED_WITH_CHILD :Q1002Cost: 2,879 Bytes: 368.690.880 Cardinality: 15.362.120      
                                                                                                        9 TABLE ACCESS FULL TABLE PARALLEL_COMBINED_WITH_PARENT STGADMIN.STG_HIERARCHY :Q1002Cost: 2,879 Bytes: 368.690.880 Cardinality: 15.362.120
                                                                                    17 PX RECEIVE PARALLEL_COMBINED_WITH_PARENT :Q1004Cost: 28,982 Bytes: 5.838.854.928 Cardinality: 243.285.622                     
                                                                                         16 PX SEND HASH PARALLEL_TO_PARALLEL SYS.:TQ10003 :Q1003Cost: 28,982 Bytes: 5.838.854.928 Cardinality: 243.285.622                
                                                                                              15 PX BLOCK ITERATOR PARALLEL_COMBINED_WITH_CHILD :Q1003Cost: 28,982 Bytes: 5.838.854.928 Cardinality: 243.285.622           
                                                                                                   14 TABLE ACCESS FULL TABLE PARALLEL_COMBINED_WITH_PARENT STGADMIN.DELTA_ACCOUNT :Q1003Cost: 28,982 Bytes: 5.838.854.928 Cardinality: 243.285.622

  • Student learning, self join

    Our teacher isnt very clear on self joins, and searching brings up too complicated of info for someone like myself just learning, so i was hoping you guys could help out. Table below:
    SQL> select * from grade;
    STD_CODE GR_LNAME GR_FNAME GR_T1 GR_T2 GR_HW GR_PR
    S1 Jordan Michael 95 80 98 90
    S2 Barkley Charles 60 100 100 60
    S3 Johnson Magic 88 98 96 98
    S4 Williams Serena 92 92 92 92
    S5 Duncan Tim 94 90 94 96
    S6 Graff Steffi 85 84 83 72
    S7 Navratilova Martina 91 88 94 95
    Need to solve this question:
    Create a view that will display names of students that have identical average grade (average of gr_t1, t2, hw, and pr)
    I learned that we needed to create a self join to sniff out the averages that were the same.
    I am pretty clueless on the logic of self join, but I made an attempt:
    CREATE VIEW SAME_GRADES2 AS SELECT S.STD_FNAME, S.STD_LNAME, (GR_T1+GR_T2+GR_HW+GR_PR)/4 AVG_GR
    FROM GRADE S, GRADE G
    WHERE S.AVG_GR=G.AVG_GR;
    i get an error on this: ORA-00904: "G"."AVG_GR": invalid identifier
    No idea. Any help for a newbie?

    sorry that last one was a syntax error... here is the result (obviously not what i need)
    GR_FNAME GR_LNAME AVG_GR
    Michael________Jordan____________90.75
    Charles________Barkley____________80
    Magic________Johnson____________95
    Martina________Navratilova_________92
    Serena________Williams____________92
    Tim________Duncan______________93.5
    Steffi________Graff _______________81
    Martina________Navratilova _________92
    Serena________Williams____________92
    9 rows selected.
    code:
    CREATE VIEW SAME_GRADES2 AS SELECT S.GR_FNAME, S.GR_LNAME, (S.GR_T1+S.GR_T2+S.GR_HW+S.GR_PR)/4 AVG_GR
    FROM GRADE S, GRADE G GROUP BY S.GR_FNAME
    WHERE (S.GR_T1+S.GR_T2+S.GR_HW+S.GR_PR)/4 = (G.GR_T1+G.GR_T2+G.GR_HW+G.GR_PR)/4;
    Edited by: user10188205 on Oct 22, 2008 4:42 PM

  • Self join please help

    I would be very grateful if someone would show me show to use the self join, I understand what is does but just don't know how to use it. I have a question from a exercise but no answer so I can't check it the question is - using temporary labels to abbreviate table names, find all the staff that earn more than 'SONG'.
    here is the table
    STAFFID SNAME JOB MGR STARTDATE SAL COMM BRANCHID
    5963 SMITH ADMIN 5209 15-NOV-00 1600 20
    5994 BATES ASSISTANT 5896 20-FEB-01 1800 100 30
    5125 CHAN ASSISTANT 5896 22-FEB-02 1550 150 30
    5665 JONES MANAGER 5938 02-MAR-01 3100 20
    5465 WILSON ASSISTANT 5896 28-OCT-00 1250 140 30
    5896 HAYAT MANAGER 5938 01-MAY-01 3100 30
    5287 CLARK MANAGER 5938 09-JUL-02 3100 10
    5887 COSTA BUYER 5665 18-APR-04 3150 20
    5938 SHAW DIRECTOR 17-NOV-01 7000 10
    5484 TURNER ASSISTANT 5896 08-OCT-01 1550 0 30
    5678 KALIM ADMIN 5887 23-APR-04 1600 20
    5009 JAMES ADMIN 5896 03-DEC-01 1600 30
    5209 SONG BUYER 5665 03-JAN-02 3000 20
    5439 SIMPSON ADMIN 5287 23-FEB-02 1600 10
    Thanks in advanced :)
    Edited by: user11093259 on 01-Dec-2010 10:19

    Hi,
    Welcome to the forum!
    Always post your best attempt at solving the problem. You'll get more specific replies that will help you learn more, and it often clarifies what you're trying to do.
    Here's a typical self-join, using the scott.dept table (which you probably have avaialble).
    SELECT     l.dname          AS lower_dname
    ,     h.dname          AS higher_dname
    FROM     scott.dept     l
    JOIN     scott.dept     h  ON     l.dname     < h.dname
    ;Output:
    LOWER_DNAME    HIGHER_DNAME
    ACCOUNTING     OPERATIONS
    ACCOUNTING     RESEARCH
    ACCOUNTING     SALES
    OPERATIONS     RESEARCH
    OPERATIONS     SALES
    RESEARCH       SALESAs you can see, this pairs every higher_dname with every dname that is less than it.
    This is very similar to your problem. The main difference is, where the query above shows every possible higher_dname (and the lower_dnames related to it), you're interested in a single, specific higher value (and the rolws with lower values related to it). You can restrict the query to show only that one, specific higher values by adding a WHERE clause. Try it. If you get stuck, ask a more specific question, and, remember, post your code.

  • Self join vs Hierarchical Queries

    Hi,
    please tel me which one 1 should use ?
    i have to get simple manger's employ list, should i use self join or hierarchical queries(CONNECT BY and prior)?
    yours sincerely

    Hi,
    944768 wrote:
    Hi,
    please tel me which one 1 should use ?
    i have to get simple manger's employ list, should i use self join or hierarchical queries(CONNECT BY and prior)?It depends on your data and your requirements.
    Whenever you have a question, please post a little sample data (CREATE TABLE and INSERT statements) for all the tables involved, so the people who want to help you can re-create the problem and test their ideas. Also post the results you want from that data, and an explanation of how you get those results from that data.
    Explain, using specific examples, how you get those results from that data.
    If you can show what the problem is using commonly available tables (suc as scott.emp, which has a 4-level hierarchy) then you don't have ot post any sample data, just the results and the explanation.
    Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
    See the forum FAQ {message:id=9360002}
    If your hierarchy consists only of 2 levels, then a self-join will probably be more efficient, simpler to code, and easier to maintain.
    If you don't know how many levels are in the hierarchy, then self-join isn't an option. Use CONNECT BY or, if you have Oracle 11.2, a recursive WITH clause.
    If you have a fixed number of levels (or an upper bound) greater than 2, then CONNECT BY (or a recursive WITH clause) will probably be best.

  • Query on Recursive Table (self-join)?

    Hi all,
    I have a table with a self join, basically an employee is managed by an employee..
    Using the following query, i'm able to query the data, giving a kind of hierarchical output, this tells me who manages who...
    SELECT LPAD(' ', 5* level) || empno
    FROM employee
    CONNECT BY prior empno = mgr
    START WITH mgr is null;This produces the following output...
    SQL> SELECT LPAD(' ', 5* level) || ep_emp_id
      2  FROM employee_on_project
      3  CONNECT BY prior ep_emp_id = ep_mgr_emp_id
      4  START WITH ep_mgr_emp_id is null;
    LPAD('',5*LEVEL)||EP_EMP_ID
         c1
              c2
                   c4
                   c5
                   c6
              c3
         c7
    7 rows selected.My question is, how can I edit the query to output only employees at the top of the hierarchy, i.e. only top managers.
    Any idea's guys??
    Cheers!

    Depending on what you mean by "top managers", but this seems the obvious solution:
    SELECT ep_emp_id
    FROM employees_on_project
    WHERE ep_mgr_emp_id IS NULLalternatively, if employees_on_project is actually complex view, and not a simple table, then this may be a better alternative:
    SELECT emp_id
    FROM (SELECT ep_emp_id, level lv
          FROM employee_on_project
          CONNECT BY prior ep_emp_id = ep_mgr_emp_id
          START WITH ep_mgr_emp_id is null)
    WHERE lv = 1TTFN
    John

  • Self Joining and Inline Query. A tricky report.

    I am stuck with a very tricky situation.Please help.This is PROD issue.
    I have written a SQL code which has 1 inline queries,and displays the right results
    with the right report output
    Dont get confused.Just go thru this.
    select   pie.id_inst_code,
             ISNULL(PN.Active, 0)                 'Active',
    from position_master_input_event pie,
    (select  insx.id_inst_xref_type,insx.id_inst_xref,count(*) 'PrimaryListing'
    from instrument ins, instrument_xref insx
    where ins.id_inst = insx.id_inst
    and   insx.flg_active = 'Y'
    and   ins.flg_active  = 'Y'
    group by insx.id_inst_xref_type,insx.id_inst_xref
    )PN
    where     id_entity = 'AGL'
    and       pie.id_inst_code *= PN.id_inst_xref
    and       pie.id_src_inst_code_type*= PN.id_inst_xref_type
    group by  pie.id_inst_code,PN.Active,
    Table :Instrument_xref
    id_inst      id_inst_xref_type    id_inst_xref  flg_active
    0372285      SE                   B0DV8Y9       Y
    0372285      IS                   GB00B03MLX29  Y
    Table :Instrument
    id_inst      id_inst_xref_type    id_inst_xref  flg_active  flg_primary_listing
    0372285      SE                   B0DV8Y9       Y           N 
    OUTPUT:
    id_inst_xref                      Active
    B0DV8Y9                           1
    PERFECT.Works fine
    2) Now comes the tricky part.:
        0372285 also has GB00B03MLX29 which has flg_active to Y and which also maps to 0372285.
        Am I right?
        New reportOutput
        id_inst_xref                      Active   PRIMARY ISIN
        B0DV8Y9                           1        1
        So,now I want a SELF JOIN this way built into the code:
        (hardcoded values work)
        (i)
        select  a.id_inst_xref
        from instrument_xref a,
             instrument_xref b
        where b.id_inst_xref ='B0DV8Y9'
        and   b.id_inst = a.id_inst
        and   b.id_inst_xref_type in ('SE','IS')
        and   a.id_inst_xref =  'GB00B03MLX29'
        (ii)
         select count(*) 'PrimaryISIN'
         from instrument ins,
             instrument_xref insx
         where ins.id_inst = insx.id_inst
         and   insx.flg_active = 'Y'
         and   ins.flg_primary_listing = 'Y'
         and   ins.flg_active = 'Y'
         And now LINKING ALL :
        select   pie.id_inst_code,
             ISNULL(PN.Active, 0)                 'Active',
        from position_master_input_event pie,
        (select  insx.id_inst_xref_type,insx.id_inst_xref,count(*) 'PrimaryListing'
         from instrument ins, instrument_xref insx
         where ins.id_inst = insx.id_inst
         and   insx.flg_active = 'Y'
         and   ins.flg_active  = 'Y'
         group by insx.id_inst_xref_type,insx.id_inst_xref
        )PN,
        (select count(*) 'PrimaryISIN'
         from instrument ins,
             instrument_xref insx
         where ins.id_inst = insx.id_inst
         and   insx.flg_active = 'Y'
         and   ins.flg_primary_listing = 'Y'
         and   ins.flg_active = 'Y'
          and     insx.id_inst_xref = ( 
                                           select  DISTINCT  a.id_inst_xref
                                            from    instrument_xref a,
                                            instrument_xref  b
                                      where b.id_inst_xref = 'B0DV8Y9'
                                          and     b.id_inst = a.id_inst
                                          and     b.id_inst_xref_type in ('SE','IS')
                                       and    a.id_inst_xref =  'GB00B03MLX29'
        where     id_entity = 'AGL'
        and       pie.id_inst_code *= PN.id_inst_xref
        and       pie.id_src_inst_code_type*= PN.id_inst_xref_type
        group by  pie.id_inst_code,PN.Active,
        THE Self join works fine as long as it is hardcoded.
        But assume there can br multiple such situations as the above,and I dont want to
        hardcode the values,how can I build the NEW REPORT by SELF JOINING.
        Please can someome help.This is a tricky one.
        Is there a better way to this

    Isn't this the same question as:
    Passing values dynamically Froman 'INLINE Query' to a 'SUB QUERY'
    and
    Another query regarding Inline Query and Self Join and pass Column Values

  • Self join with fact table in Obie 10G

    I am a newbie to obiee.I have a development requirement as follows-
    I need to find supervisors designation with the existing star RPD design. explanation is below
                                                        DIM_Designation(Desig_Wid)
                                                      |(Row_wid)
                                                      |
    DIM_EMPLOYEE--------WORKER_FACT------------DIM_Supervisor
    (Row_Wid)-----------------(Employee_Wid)
                                      (Supervisor_Wid)------------(Row_Wid)
    3 dimension is joined to fact to get employee, his supervisor and designation of employee. now i want to get the supervisor's designation? how is it possible? already employee and supervisor dimension is same W_employee_d table joined with fact as alias DIM_EMPLOYEE and DIM_SUPERVISOR. how to do self join with fact to get supervisor's designation. i do not have any supervisor_desig_wid in fact table. any help is deeply appreciated.

    Yes,Duplicate the fact table create a primary key on the newly fact table alias dimension table.So you can ur data modelling as usual.

  • How to achieve parent-child relationship using self join?

    my table structure is as follows
    parent child name
    -1     1     A1
    1     2     A2
    1     3     A3
    how to achieve the hierarchy model using self join. this can be easily achieved using "connect by prior". but how to achieve the same using self join?

    Hi,
    Yes, that's definitely possible. If you only need to display two levels from the hierarchy, a self-join is a good option. Make it an outer join if you need to show everyone on one level, regardless of whether they have a match on the other level or not; for example, if you want the output:
    child_name     child_id     parent_name     parent_id
    A1          1
    A2          2          A1          1
    A3          3          A1          1It's good that you posted some sample data. Now post the results you want from that data, and your query (what you think is the best attempt you've made so far). If you haven't tried anything so far, then look at some other simple self-join to get ideas.

  • Problem writing a XSLT to convert XML in desired format from a table having self join

    Hello,
    I have to write a style sheet to convert XML generated from XSQL into a different format. The query that I have is as follows.
    select LEVEL depth,
    'H' || hierarchy_id id,
    name,
    nvl2(parent_id, 'H' || parent_id, 0) parent_id,
    CURSOR(select LEVEL depth,
    'H' || hierarchy_id hid,
    name hname,
    nvl2(parent_id, 'H' || parent_id, 0) hparent_id,
    decode(system_id, NULL, '0', 'S' || system_id) formatted_system_id,
    system_id
    from hierarchy
    where parent_id = h.hierarchy_id
    and system_id is not null
    ) as systems
    from hierarchy h
    where system_id is null
    start with parent_id is null
    connect by prior hierarchy_id = parent_id
    The hierarchy table has a self join to itself. The selfjoin is on the hierarchyid and the parentid fields which is evident from the query.
    Here the hierarchy table contains the parent system and also the child systems underneath. The problem is that the no. of levels that it can go deep is not fixed. The output of this in sqlplus is as follows.
    Depth Hierarchyid, name parentid
    1 h1 xxx <null>
    2 h2 bbb h1
    3 h3 ccc h2
    <Cursor for systems>
    hid hname hparentid formatted_system_id systemid
    h4 ccc h2 s1 1
    h5 ccc h2 s2 2
    <Back to original data>
    Depth Hierarchyid, name parentid
    2 h6 ddd h1
    2 h7 eee h1
    The desired output required from the stylesheet is as follows
    <h id=h1 name=xxx>
    <h id=h2 name=bbb parentid=h1>
    <h id=h3 name=ccc parentid=h2>
    <h id=h4 name=fff parentid=h3 systemid=s1>
    <h id=h5 name=ggg parentid=h3 systemid=s2>
    </h>
    </h>
    <h id=h6 name=ddd parentid=h1/>
    <h id=h7 name=eee parentid=h1/>
    </h>
    Could some one guide me as to how to get this. I did write a stylesheet which gives me the following output.
    <h id=h1 name=xxx>
    <h id=h2 name=bbb parentid=h1/>
    <h id=h3 name=ccc parentid=h2/>
    <h id=h4 name=fff parentid=h3 systemid=s1>
    <h id=h5 name=ggg parentid=h3 systemid=s2>
    </h>
    <h id=h6 name=ddd parentid=h1/>
    <h id=h7 name=eee parentid=h1/>
    </h>
    As you can see I am missing the closing of the tag on the 7th line in the desired format. I have written the following stylesheet.
    <!-- Hierarchy.xsl: Transform ROWSET/ROW format to the required Hierarchy format. -->
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="node()|@*">
    <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
    </xsl:template>
    <!-- Template for matching the rowset..... -->
    <xsl:template match="HIERARCHY">
    <HIERARCHY><xsl:apply-templates/></HIERARCHY>
    </xsl:template>
    <!-- Template for matching the row .... -->
    <xsl:template match="HELEMENT">
    <xsl:choose>
    <xsl:when test="PARENT_ID=0">
    <helement id="{ID}" name="{NAME}" parentid="{PARENT_ID}"/>
    </xsl:when>
    <xsl:when test="PARENT_ID!='0'">
    <helement2 id="{ID}" name="{NAME}" parentid="{PARENT_ID}">
    <xsl:for-each select="SYSTEMS/SYSTEMS_ROW">
    <helement3 id="{HID}" name="{HNAME}" parentid="{HPARENT_ID}" systemid="{FORMATTED_SYSTEM_ID}">
    </helement3>
    </xsl:for-each>
    </helement2>
    </xsl:when>
    <xsl:otherwise>
    </xsl:otherwise>
    </xsl:choose>
    </xsl:template>
    </xsl:stylesheet>
    Is there any way of achieving this. Any help would be appreciated. I am using XSQL to generate first the basic XML output and then applying stylesheet to achieve the desired output.
    Sincerely,
    D

    Hello,
    I have to write a style sheet to convert XML generated from XSQL into a different format. The query that I have is as follows.
    select LEVEL depth,
    'H' || hierarchy_id id,
    name,
    nvl2(parent_id, 'H' || parent_id, 0) parent_id,
    CURSOR(select LEVEL depth,
    'H' || hierarchy_id hid,
    name hname,
    nvl2(parent_id, 'H' || parent_id, 0) hparent_id,
    decode(system_id, NULL, '0', 'S' || system_id) formatted_system_id,
    system_id
    from hierarchy
    where parent_id = h.hierarchy_id
    and system_id is not null
    ) as systems
    from hierarchy h
    where system_id is null
    start with parent_id is null
    connect by prior hierarchy_id = parent_id
    The hierarchy table has a self join to itself. The selfjoin is on the hierarchyid and the parentid fields which is evident from the query.
    Here the hierarchy table contains the parent system and also the child systems underneath. The problem is that the no. of levels that it can go deep is not fixed. The output of this in sqlplus is as follows.
    Depth Hierarchyid, name parentid
    1 h1 xxx <null>
    2 h2 bbb h1
    3 h3 ccc h2
    <Cursor for systems>
    hid hname hparentid formatted_system_id systemid
    h4 ccc h2 s1 1
    h5 ccc h2 s2 2
    <Back to original data>
    Depth Hierarchyid, name parentid
    2 h6 ddd h1
    2 h7 eee h1
    The desired output required from the stylesheet is as follows
    <h id=h1 name=xxx>
    <h id=h2 name=bbb parentid=h1>
    <h id=h3 name=ccc parentid=h2>
    <h id=h4 name=fff parentid=h3 systemid=s1>
    <h id=h5 name=ggg parentid=h3 systemid=s2>
    </h>
    </h>
    <h id=h6 name=ddd parentid=h1/>
    <h id=h7 name=eee parentid=h1/>
    </h>
    Could some one guide me as to how to get this. I did write a stylesheet which gives me the following output.
    <h id=h1 name=xxx>
    <h id=h2 name=bbb parentid=h1/>
    <h id=h3 name=ccc parentid=h2/>
    <h id=h4 name=fff parentid=h3 systemid=s1>
    <h id=h5 name=ggg parentid=h3 systemid=s2>
    </h>
    <h id=h6 name=ddd parentid=h1/>
    <h id=h7 name=eee parentid=h1/>
    </h>
    As you can see I am missing the closing of the tag on the 7th line in the desired format. I have written the following stylesheet.
    <!-- Hierarchy.xsl: Transform ROWSET/ROW format to the required Hierarchy format. -->
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="node()|@*">
    <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
    </xsl:template>
    <!-- Template for matching the rowset..... -->
    <xsl:template match="HIERARCHY">
    <HIERARCHY><xsl:apply-templates/></HIERARCHY>
    </xsl:template>
    <!-- Template for matching the row .... -->
    <xsl:template match="HELEMENT">
    <xsl:choose>
    <xsl:when test="PARENT_ID=0">
    <helement id="{ID}" name="{NAME}" parentid="{PARENT_ID}"/>
    </xsl:when>
    <xsl:when test="PARENT_ID!='0'">
    <helement2 id="{ID}" name="{NAME}" parentid="{PARENT_ID}">
    <xsl:for-each select="SYSTEMS/SYSTEMS_ROW">
    <helement3 id="{HID}" name="{HNAME}" parentid="{HPARENT_ID}" systemid="{FORMATTED_SYSTEM_ID}">
    </helement3>
    </xsl:for-each>
    </helement2>
    </xsl:when>
    <xsl:otherwise>
    </xsl:otherwise>
    </xsl:choose>
    </xsl:template>
    </xsl:stylesheet>
    Is there any way of achieving this. Any help would be appreciated. I am using XSQL to generate first the basic XML output and then applying stylesheet to achieve the desired output.
    Sincerely,
    D

  • Oracle query with out using self join

    hi friends,
    i have one table for exeample PERSTATUS
    pk/fK STUDENT NUMBER SUBJECT MARKS STATUS
    1 ACCOUNTS 15 RED
    1 MATHS 35 YELLOW
    1 SCINECE 45 GREEN
    2 ACCOUNTS 55 BROWN
    2 MATHS 35 YELLOW
    2 SCINECE 45 GREEN
    3 ACCOUNTS 15 RED
    3 MATHS 35 YELLOW
    3 SCINECE 45 GREEN
    i want students how status is both red and yellow so i am using self join
    i want students status is both red and yellow so i am using self join
    SELECT PS.STUDENTNUMBER,PS.STATUS,PS.STATUS1 FROM PERSTATUS PS ,PERSTATUS PS1
    WHERE PS.STUDENTNUMBER-PS1.STUDENTNUMER
    PS.STATUS='RED' AND PS1.STAUTS='YELLOW'
    i want students status is both RD and YELLOW AND GREEN so i am using self join( two self joinS}
    SELECT PS.STUDENTNUMBER,PS.STATUS,PS.STATUS,PS2.STATUS FROM PERSTATUS PS ,PERSTATUS PS1,PERSTATUS PS2
    WHERE PS.STUDENTNUMBER-PS1.STUDENTNUMER AND PS.STUDENTNUMBER-PS2.STUDENTNUMBER
    PS.STATUS='RED' AND PS1.STAUTS='YELLOW' AND PS2.STAUTUS='GREEN'
    if i require MORE STATUS then more self joins required, is there any alternative to achive this
    and if results comes in multiple rows are accepted (since with the above query result will come in single row)
    i tried to use group by (studentnumber,status) with status='red' and status='yellow'
    but it is not possible could you povidet he solution

    Hi,
    Whenever you have a problem, please post CREATE TABLE and INSERT statements for your sample data, and the exact results you want from that data. Explain how you get those results from that data.
    See the forum FAQ {message:id=9360002}
    Here's an example of how to post the sample data:
    CREATE TABLE     perstatus
    (       studentnumber     NUMBER
    ,     subject          VARCHAR2 (10)
    ,     marks          NUMBER
    ,     status          VARCHAR2 (10)
    INSERT INTO perstatus (studentnumber, subject,    marks, status)
           VALUES           (1,           'ACCOUNTS', 15,       'RED');
    INSERT INTO perstatus (studentnumber, subject  ,  marks, status)
           VALUES           (1,           'MATHS',        35,       'YELLOW');
    INSERT INTO perstatus (studentnumber, subject,    marks, status)
           VALUES           (1,           'SCINECE',  45,       'GREEN');
    INSERT INTO perstatus (studentnumber, subject,    marks, status)
           VALUES           (2,           'ACCOUNTS', 55,       'BROWN');
    INSERT INTO perstatus (studentnumber, subject  ,  marks, status)
           VALUES           (2,           'MATHS',        35,       'YELLOW');
    INSERT INTO perstatus (studentnumber, subject,    marks, status)
           VALUES           (2,           'SCINECE',  45,       'GREEN');
    INSERT INTO perstatus (studentnumber, subject,    marks, status)
           VALUES           (3,           'ACCOUNTS', 15,       'RED');
    INSERT INTO perstatus (studentnumber, subject  ,  marks, status)
           VALUES           (3,           'MATHS',        35,       'YELLOW');
    INSERT INTO perstatus (studentnumber, subject,    marks, status)
           VALUES           (3,           'SCINECE',  45,       'GREEN');You were on the right track, thinking about GROUP BY. You're interested in something about the whole group of rows that has the same studentnumber. Looking at any individual row won't tell you if that row is part of the group you're interested in or not.
    If you want to see information about the group as a whole, you can do the whole job with GROUP BY. In this case, studnetnumber is the only thing that an entire group has in common. If you wanted to see the studentnumbers that had both RED and YELLOW, that is:
    STUDENTNUMBER
                1
                3here's one way you could do it:
    SELECT       studentnumber
    FROM       perstatus
    WHERE       status     IN ('RED', 'YELLOW')
    GROUP BY  studentnumber
    HAVING       COUNT (DISTINCT status) = 2  -- That is, both RED and YELLOW
    ORDER BY  studentnumber
    ;But say you wanted to see details about individuals in the group; for example, say we want to see all the columns for students that have all 3 of RED, YELLOW and GREEN, like this:
    STUDENTNUMBER SUBJECT         MARKS STATUS
                1 SCINECE            45 GREEN
                1 ACCOUNTS           15 RED
                1 MATHS              35 YELLOW
                3 SCINECE            45 GREEN
                3 ACCOUNTS           15 RED
                3 MATHS              35 YELLOWWe used the aggregate COUNT function earlier, but aggregate functions require collapsing the results down to one row per group.
    However, most of the aggregate functions, like COUNT, have analytic counterparts, that can give the same results without collapsing the result set. Here's one way to get the results above, using the analytic COUNT function:
    WITH     got_cnt          AS
         SELECT  studentnumber, subject, marks, status
         ,     COUNT ( DISTINCT CASE
                                   WHEN  status  IN ('RED', 'YELLOW', 'GREEN')
                             THEN  status
                               END
                    ) OVER (PARTITION BY  studentnumber)     AS cnt
         FROM    perstatus
    SELECT    studentnumber, subject, marks, status
    FROM       got_cnt
    WHERE       cnt  = 3
    ORDER BY  studentnumber
    ,            status
    ;

  • Oracle doc inconsistent on materialize view with union all and self joins

    First of all, I can't seem to create a materialized view containing self-joins AND union all. Is it possible?
    I checked Oracle 9i (my version: PL/SQL Release 9.2.0.4.0 - Production) documentation and I get different answers (or so it seems to me).
    First I saw this: "The COMPATIBILITY parameter must be set to 9.0 if the materialized aggregate view has inline views, outer joins, self joins or grouping sets and FAST REFRESH is specified during creation..."
    Did you see the part about 'self joins' in there? I did and I was pumped because that seems to say that you CAN have 'self joins' (and my compatibility is 9.2...)
    BUT
    In the very same document I also found "Oracle does not allow self-joins in materialized join views." (rage)
    You can see the document I am speaking of here: http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96520/mv.htm#574889
    Whenever I try to create the mview I get the following error. (
    In any caseORA-01446 cannot select ROWID from view with DISTINCT, GROUP BY, etc.

    First of all, I can't seem to create a materialized view containing self-joins AND union all. Is it possible?
    I checked Oracle 9i (my version: PL/SQL Release 9.2.0.4.0 - Production) documentation and I get different answers (or so it seems to me).
    First I saw this: "The COMPATIBILITY parameter must be set to 9.0 if the materialized aggregate view has inline views, outer joins, self joins or grouping sets and FAST REFRESH is specified during creation..."
    Did you see the part about 'self joins' in there? I did and I was pumped because that seems to say that you CAN have 'self joins' (and my compatibility is 9.2...)
    BUT
    In the very same document I also found "Oracle does not allow self-joins in materialized join views." (rage)
    You can see the document I am speaking of here: http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96520/mv.htm#574889
    Whenever I try to create the mview I get the following error. (
    In any caseORA-01446 cannot select ROWID from view with DISTINCT, GROUP BY, etc.

  • How to resolve Self Joins in OBIEE

    Hi All
    Could any one help how to resolve the Self Join relations in OBIEE (ex. "SCOTT.EMP" table has "EMPNO" column which is referenced by "MGR" column in the same table.
    Request:
    Need to drill down from the Top manager to his employees and so on
    Another example can be applied for reporting the Organisation Chart

    This is a great article that shows ho to do the Alias:
    Adding an Alias table within the BI physical layer using Oracle BI Administration Tool
    http://www.mandsconsulting.com/adding-an-alias-table-within-oracle-bi-administration-tool
    Thanks
    Subra

  • Need help with self join query

    Hello,
    I have table A with the following data
    oid parent_oid
    10 4
    4 2
    2 2
    12 6
    6 6
    parent_oid is the parent of oid. I'd like a query that shows the final parent of the oid. The result should show the following
    oid final parent
    10 2
    4 2
    2 2
    12 6
    6 6
    I'm using Oracle 10g. I'm familiar with self joins, but that alone will not do the job. Thanks!

    Hi,
    arizona9952 wrote:
    ... I'm familiar with self joins, but that alone will not do the job.You're absolutely right!
    A 2-way self join would work for rows have no parent, or rows that are directly connected to their final ancestor (such as oid=4), but not for anything farther away.
    A 3-way self-join would work for one more level away from the final row, but no more. That would be enough for the small set of sample data that you posted, but it would not work if you added a new row with parent_id=10.
    An N-way self-join would work for up to N+1 levels, but no more.
    You need something that can go any number of levels, such as CONNECT BY:
    SELECT     CONNECT_BY_ROOT oid     AS oid
    ,     parent_oid          AS final_parent
    FROM     a
    WHERE     CONNECT_BY_ISLEAF     = 1
    CONNECT BY     oid     = PRIOR parent_oid
         AND     oid     != parent_oid
    ;Edited by: Frank Kulash on Feb 22, 2010 7:09 PM
    Upon sober reflection, I think that a Top-Down query, like the one below, would be more efficient than a Bottom-Up query, like the one above:
    SELECT     oid
    ,     CONNECT_BY_ROOT     parent_oid     AS final_parent
    FROM     a
    START WITH     parent_oid     = oid
    CONNECT BY     parent_oid     = PRIOR oid
         AND     oid          != PRIOR oid
    ;

Maybe you are looking for