Self join in the HR schema

I'm a beginner going though a tutorial on joins using the HR schema:
an example of a self join was given as:
SELECT e.last_name AS Employee, m.last_name AS Manager
FROM employees e INNER JOIN employees m
ON (e.manager_id = m.employee_id);
this executes correctly, giving a column of Employee's name and their manager's name . However, I'm having trouble wrapping my head around the ON clause in this statement.
For example if I change the ON clause so that the statement is:
SELECT e.last_name AS Employee, m.last_name AS Manager
FROM employees e INNER JOIN employees m
ON (m.manager_id = e.employee_id);
I no longer get the correct answer but I'm not sure why?

You are getting different result because:
993451 wrote:
I'm a beginner going though a tutorial on joins using the HR schema:
an example of a self join was given as:
SELECT e.last_name AS Employee, m.last_name AS Manager
FROM employees e INNER JOIN employees m
ON (e.manager_id = m.employee_id);
earlier you were joining employee's manager_id with manager's employee_id.
this executes correctly, giving a column of Employee's name and their manager's name . However, I'm having trouble wrapping my head around the ON clause in this statement.
For example if I change the ON clause so that the statement is:
SELECT e.last_name AS Employee, m.last_name AS Manager
FROM employees e INNER JOIN employees m
ON (m.manager_id = e.employee_id);
now you are joining manager's manager_id with employee's employee_id
I no longer get the correct answer but I'm not sure why?
Now, can you make out the difference between the logic you are applying.
Regards,
Ankit Rathi
http://oraclenbeyond.blogspot.in

Similar Messages

  • Do Outer Joins as well as Self Joins Affect the Performence of a Query ??

    4 Tables A,B,C,D.
    1 View V Based
    Each of the tables having 1 and only one primary key and a few NOT NULL columns.
    Now my Query selects from A,B,C,D,V with mapping Table A columns with all other Table(B,C,D,V) Primary Key Columns using Left Outer Join.
    Select A.a1,A.a2,A.a3,A.a4,B1.ba,B2.bb,B3.bc,B4.bd,C.c1,D.d1 from (((((((A left outer join B B1 on A.ba=B1.ba) left outer join B B2 on A.bb=B2.bb) left outer join B B3 on A.bc=B3.bc)left outer join B B4 on A.bd=B4.bd)left outer join C on A.c1=C.c1)left outer join D on A.d1=D.d1) left outer join V on A.v1 = V.v1) order by 1;
    In this case will the query design effect the Performence???... As this query is taking a long time. As for as Indexes are there on these tables only default Indexes due to Primary, Unique as well as Foreign key only.... Hence table structure is very simple and straight. I need a suggession in such a manner that without making changes to the Table (I am not even allowed to include a single Index to them) ...can the query be modified to optimise the performence??

    Each change to a query can effect the performance.
    Your query looks straight and simple. Maybe you could increase the performance by simply removeing the order by criteria.
    This requires a sort and a sort can be slow, especially when the resulting dataset is very large.
    If there are indexes on all foreign keys and you join using those FKs then there should be no problem with the index structure.
    I can't say whether it would be better to use an index or not. but you can look at the execution plan and check what the CBO wants to do.
    Make sure that all statistics are up to date. You could consider to run an additional dbms_stats.gather_table_stats with compute in the test environment, just to see if the execution plan changes after this.
    For further ideas search this forum for the thread "When your query takes too long".

  • How to re-write this self join update using a CTE

    I would like to improve my performance on this update statement and would like to try re-writing using a CTE:
    UPDATE "usr_sessions" "a" SET "is_ended_at_trustable" = 't'
          WHERE (
            EXISTS (
              SELECT 1
              FROM "usr_sessions" "b"
              WHERE "a"."ended_at" = "b"."started_at"
                AND "a"."usr_space_id" = "b"."usr_space_id"
                AND "a"."account_id" = "b"."account_id"
          ) ) AND "a"."is_ended_at_trustable" IS NULL
    Any help is greatly appreciated!  Open to other suggestions as well if there is a better way!

    If I understood your description correctly, here's a way to accomplish the same thing, while dodging the need for the self join.   The update itself won't be any faster, but the overall query leading to the update will likely be faster sans self-join.
      (If my interpretation wasn't exactly what you meant, tweak the "partition by" clause).
    MERGE is generally considered better then UPDATE, but your particular update isn't at risk for the shortcomings of update (still, Merge is newer, cooler, and more trustworthy).
    Setup_Example_Data:
    Declare @Usr_Sessions table (account_id int, usr_space_id int, is_ended_at_Trustable Char(1), started_at varchar(99), ended_at varchar(99))
    Insert @Usr_Sessions
    Select 1, 10, 't', 'A1', 'A1'
    UNION ALL Select 2, 20, 'f', 'B1', 'B2'
    UNION ALL Select 3, 30, NULL, 'C1', 'C1'
    UNION ALL Select 4, 40, NULL, 'D1', 'D2'
    UNION ALL Select 5, 50, NULL, 'E1', 'E2'
    UNION ALL Select 5, 51, NULL, 'E3', 'E3'
    UNION ALL Select 6, 61, NULL, 'F1', 'F2'
    UNION ALL Select 6, 62, 't', 'F3', 'F3'
    UNION ALL Select 6, 62, 'f', 'F4', 'F4'
    Select 'Before', * from @Usr_Sessions
    OP_Query:
    BEGIN TRAN
    UPDATE A SET is_ended_at_trustable = 't' from @usr_Sessions A-- Select * from @Usr_Sessions "a" --
    WHERE (
    EXISTS (
    SELECT 1
    FROM @usr_sessions "b"
    WHERE "a"."ended_at" = "b"."started_at"
    AND "a"."usr_space_id" = "b"."usr_space_id"
    AND "a"."account_id" = "b"."account_id"
    ) ) AND "a"."is_ended_at_trustable" IS NULL
    Select 'After 1', * from @Usr_Sessions
    ROLLBACK TRAN /* Just to reset test data to original form, so second query below runs against original data */
    Dodge_Self_Join:
    With X as
    Select *
    , count(case when started_at = ended_at and is_ended_at_trustable is null then 'x' else null end)
    over(partition by account_id, usr_space_id) as Updatable
    From @Usr_Sessions
    Update X
    set is_ended_at_Trustable = 'T'
    where Updatable > 0 -- EDIT -- fixed error, previously said "updatable = 1"
    Select 'After 2', * from @Usr_Sessions

  • 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 in Discoverer Admin.

    Hi,
    We have a requirement in which we have to leave an option for self join for the users so that they should be able to change the join depending on their requirements.
    So basically they want this option to be open for them in Disc Admin.
    But i'm afraid as there is no such option for self join in Disc Admin...
    So any work arounds for this??
    Thanks in advance.

    Hi,
    I will try and explain, but I am not entirely sure what you actually want to do.
    But suppose you have a folder F1 which maps to a table T1 and your users want to join T1 to itself but different users want to use different join conditions. Then you can create another complex folder F2 in the EUL and drag all the items from F1 into F2 to create another folder mapping on to T1. Then create a new item in the EUL in the F1 folder called join1 by just putting 1 in the calculation so that the join1 item always returns 1. Then in the same way create a join1 item in the F2 folder. This you will be able to create a join between join1 item in F1 and the join1 item in F2.
    Your users will then be able to add items from both the F1 and F2 folders into a workbook. They will have to create the actual join between the folders by creating a condition in the workbook joining F1 columns to F2 columns.
    Hope that is clear.
    Rod West

  • How to permit multiple workspaces to access the same schema?

    Hello,
    When creating a new workspace (version 3.2), I am getting the following warnings:
    "Warning: The requested schema already exists. Warning: The requested schema is already assigned to one or more workspaces. Please ensure that giving multiple workspaces access to the same schema is permitted by the security policies at your site before approving this request."
    How do I "ensure that giving multiple workspaces access to the same schema is permitted"?
    What are the advantages/disadvantages of doing so?
    Thanks,
    Gabor

    The correct answer to it would have been: I use manual provisioning.I didn't ask a detailed enough question. What I am wondering is how you are set up to to workspace provisioning at your site. In apex_admin, if you navigate to Home>Manage Service>Instance Settings there is a radio group like:
    Provisioning Status:      
    0 Manual - An administrator manually creates each workspace
    0 Request - Link displayed on login page enabling users to request workspaces
    0 Email Verification - Workspace created after email address is verified by the user
    The help text for this is:
    Provisioning Status:      
    Determines how the process of provisioning (or creating) a workspace works for your development instance. Options include:
        * Manual - An Application Express administrator manually creates new workspaces and notifies the Workspace administrator of the login information.
        * Request - Users request workspaces directly in a self-service fashion. Selecting this option displays a link on the Login page enabling users to request a workspace. When a user requests a workspace, each request is submitted to a queue for approval.
        * Email Verification - Works similar to Request except each user receives an initial email containing a link. Clicking this link validates the user's email address before the request is processed.
    Note: To enable users to request a workspace using a link on the Login page, you must choose Request or Email Verification. If you select Manual, no link appears on the login page.How is yours set up?
    As to the first original question (How do I "ensure that giving multiple workspaces access to the same schema is permitted"?), I still do not know.Whether it is permitted or not is a decision made by the apex site administrator who approves/declines workspace requests. Whether it ought to be permitted is a different question and is really same as your second question which involves issues you said you are now starting to understand better. So I think we've covered your original questions. If not, please elaborate.
    As to the last subject (How did the hidden workspace get created and how do I get rid of id? What happens if I don't?), this happened at work, so I can only tell you more on Monday (luckily...). Until then, here is what I remember. The work space was created, which is proven by the fact that when I want to create a new workspace with the same name, I am getting an error, which says that a workspace with that name already exists. However, I cannot delete the workspace, since it show up nowhere.No hidden workspace got created. I'm pretty sure the request is just in the queue waiting to be approved/declined. In the meantime a workspace with the same name cannot be requested.
    By the way, how do you quote some text here? I just put a '>' in the first character position before the text to quote. You can also use the " rich text icon above the text pane.
    Scott

  • Spatial query on join view in another schema

    Background:
    I have a schema with tables containing four spatial columns per table. I have a second schema that contains join views of the tables in the first schema. The join view consists of the attributes and any other tabular data that is joined via foreign key to non-spatial tables and one of the four geometry columns. I have a third schema that owns no database objects of its own, but has select privilege to the second schema's view objects.
    We are using Oracle 10.2.0.2 on a windows platform.
    This worked in 9i, the problem only presented itself when we migrated to 10g.
    Problem:
    When I run a spatial query on a join view in the second schema(the schema that owns the object), it runs and returns results in about a second. When I run the exact same query in the third schema it routinely takes 20-30 seconds.
    Here is the query that I run in both schemas with varying query times:
    SELECT COUNT(*)
    FROM two.join_view_a A
    WHERE (MDSYS.SDO_FILTER(A.GEOM, SDO_GEOMETRY(2003,8307,NULL,SDO_ELEM_INFO_ARRAY(1,1003,3),SDO_ORDINATE_ARRAY(26.6396,26.5708,43.346,34.4083)),'QUERYTYPE=WINDOW')='TRUE');
    Question:
    Why does this happen?
    What can I do to fix this problem?
    Thanks,
    John

    Have a read of this posting: Oracle spatial view runing slow as different user
    There are details there about the 'optimizer_secure_view_merging' parameter and the effect it can have on cross schema views in 10.2

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

  • 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

Maybe you are looking for

  • Error 1017 received logging on to the standby

    Hi anyone, Please help me... i have database running on Oracle 10gR1 EE (10.1.0.4.0) on Linux Red Hat. and this server is replicate to DR server for backup. we change 'SYS' password about a week ago and nothing occur until today, the database is not

  • Bluetooth Audio to car stereo

    Newbie question: I would like to be able to feed music and radio from my macbook to a Pioneer FH-P800BT car radio via Blue tooth connection. I can connect and transfer data to the radio using its hands free mode and the "headset" option on the mac. I

  • Iphoto starts but then quits.

    Hey, The names Stu My iPhoto keeps quitting about 30 seconds after I start it up.  I have seriously tried everything. here's the crash report, any ideas? Process:         iPhoto [158] Path:            /Applications/iPhoto.app/Contents/MacOS/iPhoto Id

  • Help required in reading freight price for PO item. See below code.

    H All, I have a requirement to read frieght cost for each PO item. Please see the below code and let me know is this approach is correct or not. * Fetch PO header details for selected criteria   SELECT ebeln                         "Purchasing docume

  • How do I make  a 2nd Address book?

    I want to create a group and change the cards in that group without the original card changing? I can do that with NOW Contact and could do that years ago with Dynodex. Addess Book works like iTunes, with a Library and Playlist format. How do I creat