SQL issue - how to do multiple outer self-joins

Hi all,
I am having a problem with what I thought would be a rather simple query, but it has me stumped at this point. I have 2 tables, PHONE and PHONE_DETAIL. The PHONE table is just a main list that has ID's, and a country (and other info, but I've simplified it for this example). For each ID in the PHONE table, there could be 0, 1 or many records in the PHONE_DETAIL table - each record in PHONE_DETAIL is designated as either a Primary, Secondary, or Tertiary number. I need to have a query that pulls for ALL records in the PHONE table, joining to the PHONE_DETAIL table, that pivots them out, showing one line per ID. So if one ID from PHONE has 3 records in PHONE_DETAIL (one primary, one secondary, and one tertiary), then I just want to see one resulting line in the query output, showing all 3 together.
Setup:
create table phone (
id number,
country varchar2(20));
insert into phone values (21, 'Australia');
insert into phone values (22, 'Australia');
insert into phone values (23, 'Australia');
insert into phone values (135, 'Australia');
insert into phone values (136, 'Australia');
insert into phone values (137, 'Australia');
create table phone_detail (
phone_id number,
termination_type varchar2(100),
termination_number varchar2(100));
insert into phone_detail values (135, 'Primary', '132-456-7890');
insert into phone_detail values (136, 'Primary', '231-098-8765');
insert into phone_detail values (137, 'Primary', '789-789-7890');
insert into phone_detail values (137, 'Secondary', '234-345-4567');
insert into phone_detail values (137, 'Tertiary', '567-123-1234');
select * from phone;
ID COUNTRY
21 Australia
22 Australia
23 Australia
135 Australia
136 Australia
137 Australia
select * From phone_detail;
PHONE_ID TERMINATION_TYPE TERMINATION_NUMBER
135 Primary 132-456-7890
136 Primary 231-098-8765
137 Primary 789-789-7890
137 Secondary 234-345-4567
137 Tertiary 567-123-1234
And here is the query that I have so far:
SELECT p.ID,
d1.TERMINATION_NUMBER AS primary_number,
d2.TERMINATION_NUMBER AS secondary_number,
d3.TERMINATION_NUMBER AS tertiary_number
FROM PHONE p,
PHONE_DETAIL d1,
PHONE_DETAIL d2,
PHONE_DETAIL d3
WHERE p.id = d1.phone_id(+)
AND nvl(d1.termination_type, 'Primary') = 'Primary'
and p.id = d2.phone_id(+)
AND nvl(d2.termination_type, 'Secondary') = 'Secondary'
and p.id = d3.phone_id(+)
AND nvl(d3.termination_type, 'Tertiary') = 'Tertiary'
AND p.country = 'Australia';
ID PRIMARY_NUMBER SECONDARY_NUMBER TERTIARY_NUMBER
137 789-789-7890 234-345-4567 567-123-1234
23
22
21
As you can see, it is working that it pulls the ID's 21, 22, 23, even though they don't have any associated records in the PHONE_DETAIL table (I want this to happen). However, it is NOT pulling the records for ID 135 or 136, which each have a Primary record in PHONE_DETAIL (but no secondary or tertiary). The only way I can think of at this point is to do a big ugly UNION query, with 3 different queries, but there has got to be a smarter way to do this. Any ideas?
Thanks,
Brad
[email protected]

And I knew this would happen - that I would get it figured out right after I posted here. I just needed to add a few more (+) to the query, like this:
SELECT p.ID,
d1.TERMINATION_NUMBER AS primary_number,
d2.TERMINATION_NUMBER AS secondary_number,
d3.TERMINATION_NUMBER AS tertiary_number
FROM PHONE p,
PHONE_DETAIL d1,
PHONE_DETAIL d2,
PHONE_DETAIL d3
WHERE p.id = d1.phone_id(+)
AND nvl(d1.termination_type(+), 'Primary') = 'Primary'
and p.id = d2.phone_id(+)
AND nvl(d2.termination_type(+), 'Secondary') = 'Secondary'
and p.id = d3.phone_id(+)
AND nvl(d3.termination_type(+), 'Tertiary') = 'Tertiary'
AND p.country = 'Australia';

Similar Messages

  • I am in sql plus how do I find out what database I am in?

    I am in sql plus how do I find out what database I am in? is there a sql command for that...

    select name from v$database;
    or
    select sys_context('userenv', 'DB_NAME') from dual;

  • IPhone 6 Plus - IOS 8 Wifi Issue - How can we rule out a hardware issue

    iPhone 6 IOS 8 Wifi Issue - How can we rule out hardware
    With all the post about Wifi issue, could it be hardware and not software.  Anyone know how to diagnosis the difference.

    Hi Lady Engineer,
    If you are having an issue with Wi-Fi on your iPhone, I would suggest that you troubleshoot using the steps in this article - 
    iOS: Troubleshooting Wi-Fi networks and connections
    Thanks for using Apple Support Communities.
    Best,
    Brett L 

  • I'm having network security issues, how can I find out who has been seeing my information on my laptop

    How can I find out who has been loging on or attached to my network and on to my computer remotly.

    Dartrath--
    Please give us much more pecific information as to why you think someone is doing this?
    What signs and symptoms are you experiencing?

  • 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

  • How to get multiple out parameters from a pl/sql stored procedure in ADF Jdeveloper 11g release2

    I´m trying to call from AppModuleImpl a stored procedure from my oracle DB which receives one input parameter and returns 5 out parameters. 
    I´m using jdeveloper 11g release2  ADF and I have created a java bean "ProRecallPlatesBean " with the atributes and accesors and I serialize it. just like in this article http://docs.oracle.com/cd/E24382_01/web.1112/e16182/bcadvgen.htm#sm0297
    This is my code so far:
    public ProRecallPlatesBean getCallProRecallPlates(String numPlates) {
    CallableStatement st = null;
    try {
              // 1. Define the PL/SQL block for the statement to invoke
              String stmt = "begin CTS.Pk_PreIn.proRecallPlates(?,?,?,?,?,?); end;";
              // 2. Create the CallableStatement for the PL/SQL block
              st = getDBTransaction().createCallableStatement(stmt,0);
              // 3. Register the positions and types of the OUT parameters
              st.registerOutParameter(2,Types.VARCHAR);
    st.registerOutParameter(3,Types.VARCHAR);
    st.registerOutParameter(4,Types.VARCHAR);
    st.registerOutParameter(5,Types.VARCHAR);
    st.registerOutParameter(6,Types.VARCHAR);
    // 4. Set the bind values of the IN parameters
    st.setString(1,numPlates);
    // 5. Execute the statement
    st.executeUpdate();
    // 6. Create a bean to hold the multiple return values
    ProRecallPlatesBean result = new ProRecallPlatesBean();
    // 7. Set values of properties using OUT params
    result.setSpfVal(st.getString(2));
    result.setTransportTypeVal(st.getString(3));
    result.setTransportCompanyVal(st.getString(4));
    result.setCompanyDescrVal(st.getString(5));
    result.setDGAPrint(st.getString(6));
    // 8. Return the result
    return result;
    } catch (SQLException e) {
    throw new JboException(e);
    } finally {
    if (st != null) {
    try {
    // 9. Close the JDBC CallableStatement
    st.close();
    catch (SQLException e) {}
    In Jdeveloper I went into AppModule.xml JAVA>Client Interface section and expose "getCallProRecallPlates" Then I can see "getCallProRecallPlates" in Data Controls, I drag and drop it to a JSF page, an input text component and a button are generated in order to put in there the procedure input parameter (numPlates).
    I don't know if I'm on the right track.
    When I click the button, the "result" variable is supposed to be filled with data from the stored procedure. I want each of those values to be displayed in Output text or input text adf components but I dont know how. Thank you very much in advance I´m a newbie and i'll appreciate your help!

    What version are you on?
    Works fine for me on my 11g:
    SQL> create or replace procedure testxml (clob_out out clob)
      2  is
      3     l_clob   clob;
      4     l_ctx    dbms_xmlquery.ctxhandle;
      5  begin
      6     l_ctx := dbms_xmlquery.newcontext ('select * from dual');
      7     l_clob := dbms_xmlquery.getxml (l_ctx);
      8     clob_out := l_clob;
      9     dbms_xmlquery.closecontext (l_ctx);
    10  end testxml;
    11  /
    Procedure created.
    SQL>
    SQL> variable vout clob;
    SQL>
    SQL> exec testxml (:vout)
    PL/SQL procedure successfully completed.
    SQL>
    SQL> print vout
    VOUT
    <?xml version = '1.0'?>
    <ROWSET>
       <ROW num="1">
          <DUMMY>X</DUMMY>
       </ROW>
    </ROWSET>But definitely you can optimize your proc a bit: Try
    create or replace procedure testxml (clob_out in out nocopy clob)
    is
       l_ctx    dbms_xmlquery.ctxhandle;
    begin
       l_ctx := dbms_xmlquery.newcontext ('select * from dual');
       clob_out := dbms_xmlquery.getxml (l_ctx);
       dbms_xmlquery.closecontext (l_ctx);
    end testxml;
    /

  • How to use multiple outer join in ODI

    SELECT
    Count(*)
    FROM
    student S,
    department D,
    course C
    WHERE
    D.S_Name=S.S_Name
    AND D.Dept_Name = C.Dept_Name (+)
    and S.C_Name =C.C_Name (+)
    And (D.Dept_ID = 1);
    I run this query. I got an ORA-01417 error.

    In topology change the join option to Ordered ISO
    then rewrite your query with ANSI syntax.
    SELECT
    Count(*)
    FROM
    student S join department D on D.S_Name=S.S_Name,
    student S right outer join course C on S.C_Name =C.C_Name,
    department D right outer join course C on S.C_Name =C.C_Name
    where
    (D.Dept_ID = 1);
    First verify the code in sql client befor implementing it in ODI
    Thanks,
    Sutirtha

  • After Effects CS4 | How to set multiple out destinations at once

    I know that if you have multiple items in the render queue you can control-click on the Output Module and set all of the selected items to the same Output Module.  I am wondering if there is a way to set the render destination (Output To) of multiple compositions at once as well.  It's not uncommon for me to have well over 20 compositions that all need to render to the same folder.  It becomes a pain when I need to click on each and tell them where to go individually.
    Any insights are appreciated.
    -Adam

    Exactly as Todd said.
    Mylenium

  • How to update multiple calling hours based on business partner

    Hi All,
    please help me in this issue : how to update multiple calling hours based on business partner in SAP CRM.
    Regards,
    Siva kumar.

    Check maintainance view V_TB49, add new scheduling type.

  • How to invoke multiple sessions of sql*plus thru pl/sql program

    Hi
    How to invoke multiple sessions of sql*plus thru pl/sql program.
    Thanks

    How to invoke sql*plus in a procedure?????
    I have to invoke more pl/sql sessions?????No you don't "have to".
    Look at what you are trying to do.
    You have a program running inside the PL/SQL engine. This is running nicely inside the Oracle database and is perfectly capable of issuing other SQL statements, PL/SQL programs etc. inside it's nice cosy Oracle environment.
    You are asking for this PL/SQL to shell out to the operating system, run an external application, for which it will have to supply a username and password (are you planning on hard coding those into your PL/SQL?), and then that external application is supposed to run more SQL or PL/SQL against the database.
    a) Why hold all this code external to the database when it can quite happily reside on the database itself and be executed through jobs or whatever.
    b) Consider what would happen if someone were to replace the external application with their own program of the same file name... they'd be able to capture the username and password for connecting to the database, therefore a major security flaw.
    The whole idea of doing what you want through external calls to SQL*Plus is ridiculous.

  • How to get multiple records using fn-bea:execute-sql()

    Hi,
    I created Proxy service(ALSB3.0) to get records from DB table. I have used Xquery function(fn-bea:execute-sql()). Using simple SQL query I got single record, but my table having multiple records. Please suggest how to get multiple records using fn-bea:execute-sql() and how to assign them in ALSB variable.
    Regards,
    Nagaraju
    Edited by: user10373980 on Sep 29, 2008 6:11 AM

    Hi,
    Am facing the same issue stated above that I couldnt get all the records in the table that am querying in the Proxyservice.
    For example:
    fn-bea:execute-sql('EsbDataSource', 'student', 'select Name from StudentList' ) is the query that am using to fetch the records from the table called StudentList which contains more than one records like
    Id Name
    01 XXX
    02 YYY
    03 ZZZ
    I tried to assign the result of the above query in a variable and while trying to log the variable, I can see the below
    <student>
    <Name>XXX</Name>
    </student>
    I want to have all the records from my table in xml format but it's not coming up. I get the value only from the first row of my table.
    Please suggest.
    regards,
    Venkat

  • How to run multiple sqls in one jasper report

    Hello!
    Is there any one that can help me in integrating/ viewing my xml file to the web. I have my GUI in jsp format, the jsp makes a call to the bean class and then finally bean class hit my reports java class.The report java class generates the report and shows it in the new window.
    The problem is with writing mutiple sql queries and showing the result from multiple sql queires in one report.
    I do not know how to write multiple queries for just 1 report. I can give a simple example of my problem also.
    My report is as follows:
    First Name Middle Name Last name
    Sandeep               Pathak
    Now First and Middle Name come from 1st sql query and Last Name comes from 2nd sql query.
    I want to join the result obtained from both the sql queries in one Jasper Report (not as 2 separate sections but as one section).
    My problem is how to view my report in the web. furthermore, how to make complex query in jasperassistant, like multiple table in one query, because i�m integrating multiple query in one form or sheets of paper.
    Please help me in this.
    Thanks
    Sandeep
    Calance
    India

    Hi Sheldon,
    we never have issues when we combine standard objects, like a cliear with a load inforprovider, or the master data integration you mentioned in your document. However, from the moment we combine a script logic with a standard package (like a move) it does not work .The data package contains the task needed for the script and for the move. the process chain is called up but always comes in error in the first step (BPC modify dynamically ) ... there is also no log when checking the view status ...
    I can sent you some screenshots if you like ...
    D

  • Multiple Out put issued

    Dear All,
    I have one sales order where out put types DLO1, DLO3 and DLO4 are determined as sales order confirmation out put. The transmission medium for all of these is Print out ie external send.
    Here in the sales order multiple out puts are issued. Customer has received 5-6 mails for each output. When i go to out put determination / edit screen thre also i can see as many number of lines partaining to output types.
    Can you please help me solving this issue since i am not able to analyse from where or how this thing is happening.
    One imp thing i noted that all the out put are automatically detemined. I mean no mannual addtion of lines has happened.
    Regards,
    Vishi.

    Hi Vishi
    Please check you routine associated with your output type, suppose you have a requiremnt that is qty=5 then trigger DLO1, in such cases every time you save sales order with qty =5 output will trigger automatically.
    To avoid such cases add some code in routine that is output has already triggered then don't trigger.
    Take help of ABAPer.
    try and revert

  • How to execute sql scripts from Powershell across multiple databases

    Re: How to execute sql scripts from Powershell across multiple databases
    I have an tsql script that I want to run across a list of databases. How is the best way to do this in Powershell? Thanks.

    My example below, using just the SMO and not breaking up the batches, the ExecuteWithResults give the following error when the .sql file contains a GO. My script files are as simple as a DECLARE and then a GO.
    WARNING: SQL Script Failed
    The object of type "Microsoft.PowerShell.Commands.Internal.Format.FormatStartData" is not valid or not in the correct sequence. This is likely caused by a user-specified "format-list" comm
    and which is conflicting with the default formatting.
        + CategoryInfo          : InvalidData: (:) [out-lineoutput], InvalidOperationException
        + FullyQualifiedErrorId : ConsoleLineOutputOutOfSequencePacket,Microsoft.PowerShell.Commands.OutLineOutputCommand
    Also, when executing from the ISE, is there a way to force the ISE to release the files. I am having to close the ISE and reopen my script every time I want to make a testing change to the .sql file.
    [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")
    $scriptspath = "C:\temp\psExecuteSQLScripts\scripts"
    $SQLServer = "fidevc10"
    $SQLDB = "Bank03"
    # Create SMO Server Object
    $Server = New-Object ('Microsoft.SQLServer.Management.Smo.Server') $SQLServer
    # Get SMO DB Object
    $db = $Server.Databases[$SQLDB]
    # Load All SQL Scripts in Directory
    $scripts = Get-ChildItem -Path (Join-Path $scriptspath "*") -Include "*.sql" -Recurse
    # Loop through each script and execute
    foreach ($SQLScript in $scripts)
    $fullpath = $SQLScript.FullName
    # Read the Script File into Powershell Memory
    $reader = New-Object System.IO.StreamReader($fullpath)
    $script = $reader.ReadToEnd()
    # Execute SQL
    Write-Host "Executing $SQLScript on $SQLDB...."
    try
    $ds = $db.ExecuteWithResults($script)
    Foreach ($t in $ds.Tables)
    Foreach ($r in $t.Rows)
    Foreach ($c in $t.Columns)
    Write-Host $c.ColumnName "=" $r.Item($c)
    Write-Host "Complete"
    catch [Exception]
    Write-Warning "SQL Script Failed"
    echo $_.Exception|format-list -force
    Write-Host " " -BackgroundColor DarkCyan

  • Flash player has been installed multiple time without errors but bbc news website and even flash player help say it isn't. How do i get out of this loop? - using windows 7 ultimate and latest IE11

    flash player has been installed multiple time without errors but bbc news website and even flash player help say it isn't. How do i get out of this loop? - using windows 7 ultimate and latest IE11

    I have had the same problem for WEEKS and I cannot access any sites that use Flash. Flash has been installed on this computer since I bought it in 2012. I have allowed auto updates but for weeks the updates never get past Step 2 - is this because I do NOT want the Google Tool bar? I use NO tool bars as there is only 6 inches of vertical screen space. Is this because I uncheck wanting Chrome as a default browser?  It is already installed, I just don't use it.  I came to this site and ran the check is it installed and the system says it is either not installed or not enabled. Version 14 just downloaded about 30 minutes ago - but did not progress to Step 3 although a pop up screen came up with a finish button, which I clicked. WHAT is the problem and how do I fix it?  If this were just a compatibility bug between IE11 and Adobe they have had plenty of time to fix it.
    Stephanie HC

Maybe you are looking for

  • How can multiple users work on one source file?

    Hi There, I'm currently working on a project that I would like to hand-off to another person to finish. I've tried sending the source file located in at: Home>Movie>iMovie Projects but apparently that doesn't work as the second user is unable to work

  • Payment Program RFFORBR_D problem: the program is printing 2 copies

    Hi guys! I have a problem with the RFFOBR_D program : when I generate a payment order in F110 transaction, it generates a payment document, but with 2 copies of the last page. Do you know what is happening? Thank you! Cesar

  • All I want is a Paper Bill

    Having so much difficulty knowing 'where' to send my bill.  So far I've seen three addresses in three different states.  I have not even received my bill and of course contacting customer service is by telephone is another fiasco.  The only time I ha

  • Howto Register &  Execute Custom Oracle Reports in R11I ( 11.5.9 )

    Hii guys How do i register execute and view output of Custom Oracle Reports in R11i ( 11.5.9 ) .I have developed custom reports for HR and Payroll in Report Builder 6i. Is their a step by step tutorial ?? What to do next ?? Can somebody please guide

  • Solaris10 missing /usr/openwin directories in non-global container

    I created a global (default) and two non-global containers. The /usr/openwin directories in non-global containers are empty (while global one's are fine). Since /usr is read only in non-global containers, I can't add anything to it. questions: 1. why