Outer join on query with OR clause

hi all, i am having problem outerjoining a query with or clause
here is my data
WITH table1 AS
SELECT  'test' txt1, 'pak' txt2, 'ced' txt3, 'su' txt4 FROM dual UNION ALL
SELECT  null txt1, 'pak' txt2, 'ced2' txt3, 'su2' txt4 FROM dual UNION ALL
SELECT  null txt1, NULL txt2, 'ced3' txt3, 'su3' txt4 FROM dual UNION ALL
SELECT  null txt1, NULL txt2, null txt3, 'su3' txt4 FROM dual UNION ALL
SELECT  'text5' txt1, NULL txt2, null txt3, 'su3' txt4 FROM dual UNION ALL
SELECT  null txt1, NULL txt2, null txt3, null txt4 FROM dual
,table2 AS
SELECT 111 pid, 'test' txt1, 'pak4' txt2, 'ced' txt3, 'su' txt4 FROM dual UNION ALL
SELECT 222 pid, 'test1' txt1, 'pak' txt2, 'ced2' txt3, 'su2' txt4 FROM dual UNION ALL
SELECT 333 pid, 'test2' txt1, 'pak3' txt2, 'ced3' txt3, 'su4' txt4 FROM dual UNION ALL
  SELECT 444 pid, 'test2' txt1, 'pak3' txt2, 'ced4' txt3, 'su3' txt4 FROM dual
SELECT b.pid, a.*
from table1 a, table2 b
WHERE (a.txt1 = b.txt1 OR
       a.txt1 IS NULL AND a.txt2=b.txt2 OR
       Nvl(a.txt2, a.txt1) IS NULL AND a.txt3 = b.txt3 OR
       Nvl(a.txt2, a.txt1) IS NULL  AND a.txt3 IS NULL AND a.txt4 = b.txt4
       ) as you can see i am joining table1 and table 2. i am joining with txt1, if txt1 is null then join by txt2, if null then join by txt3 and so on.
the code above product this output
PID     TXT1     TXT2     TXT3     TXT4
===     ====     ===   ==== ====
111     test     pak      ced     su
222             pak      ced2     su2
333                     ced3     su3
444                          su3this output is partially correct. only 4 rows were display and two was left out
SELECT  'text5' txt1, NULL txt2, null txt3, 'su3' txt4 FROM dual UNION ALL
SELECT  null txt1, NULL txt2, null txt3, null txt4 FROM dual i tried using outer join but oracle complain that i cannot use outerjoin with OR clause.
can someone help modify my query to display the output below ?
PID     TXT1     TXT2     TXT3     TXT4
===    ====      ===   ====  ====
111     test     pak      ced     su
222             pak      ced2     su2
333                     ced3     su3
444                          su3
NULL  NULL   NULL    NULL   NULL
     test5

Not sure you can do it with the Oracle style outer joins, but wioth ANSI style joins it is simple, actually exactly as you had it.
SQL> set null null;
SQL> WITH table1 AS (
  2   SELECT  'test' txt1, 'pak' txt2, 'ced' txt3, 'su' txt4 FROM dual UNION ALL
  3   SELECT  null txt1, 'pak' txt2, 'ced2' txt3, 'su2' txt4 FROM dual UNION ALL
  4   SELECT  null txt1, NULL txt2, 'ced3' txt3, 'su3' txt4 FROM dual UNION ALL
  5   SELECT  null txt1, NULL txt2, null txt3, 'su3' txt4 FROM dual UNION ALL
  6   SELECT  'text5' txt1, NULL txt2, null txt3, 'su3' txt4 FROM dual UNION ALL
  7   SELECT  null txt1, NULL txt2, null txt3, null txt4 FROM dual),
  8  table2 AS (
  9   SELECT 111 pid, 'test' txt1, 'pak4' txt2, 'ced' txt3, 'su' txt4 FROM dual UNION ALL
10   SELECT 222 pid, 'test1' txt1, 'pak' txt2, 'ced2' txt3, 'su2' txt4 FROM dual UNION ALL
11   SELECT 333 pid, 'test2' txt1, 'pak3' txt2, 'ced3' txt3, 'su4' txt4 FROM dual UNION ALL
12   SELECT 444 pid, 'test2' txt1, 'pak3' txt2, 'ced4' txt3, 'su3' txt4 FROM dual)
13  SELECT b.pid, a.*
14  from table1 a
15     LEFT JOIN table2 b
16        ON (a.txt1 = b.txt1 OR
17            a.txt1 IS NULL AND a.txt2=b.txt2 OR
18            Nvl(a.txt2, a.txt1) IS NULL AND a.txt3 = b.txt3 OR
19            Nvl(a.txt2, a.txt1) IS NULL  AND a.txt3 IS NULL AND a.txt4 = b.txt4);
       PID TXT1   TXT2   TXT3   TXT4
       111 test   pak    ced    su
       222 null   pak    ced2   su2
       333 null   null   ced3   su3
       444 null   null   null   su3
null       text5  null   null   su3
null       null   null   null   nullJohn

Similar Messages

  • Outer join two tables with query search record attached to both tables

    When I create a query with two tables that have query search records attached with outer join, PS seems to do a natural join (cartesian). We are on PT8.48.
    Is there a workaround for this issue. I do not want to remove query search record on either of the tables.
    I am trying to create an Emergency contact report. I am using two tables PS_EMPLOYEES and PS_EMERGENCY_CNTCT. Here is the sql PeopleSoft query generated when I did Left outer Join.
    Query SQL:
    SELECT A.EMPLID, A.NAME, A.ADDRESS1, A.CITY, B.PRIMARY_CONTACT, B.ADDRESS1, B.CITY, B.STATE, B.POSTAL, B.RELATIONSHIP, A.DEPTID, A.JOBCODE, A.COMPANY, A.EMPL_TYPE
    FROM (PS_EMPLOYEES A LEFT OUTER JOIN PS_EMERGENCY_CNTCT B ON A.EMPLID = B.EMPLID ), PS_EMPLMT_SRCH_QRY A1, PS_PERS_SRCH_QRY B1
    WHERE A.EMPLID = A1.EMPLID
    AND A.EMPL_RCD = A1.EMPL_RCD
    AND A1.OPRID = 'SREESR'
    AND (B.EMPLID = B1.EMPLID OR B.EMPLID IS NULL )
    AND B1.OPRID = 'PS'
    Appreciate any help.

    I think there are fixes for this issue in later tools releases (Report ID 1544345000). I'm not sure about 8.48, but you might try the workaround documented in
    E-QR: Left Outer Joins with Security Records are returning unexpected results [ID 651252.1]
    on Oracle Support.
    Regards,
    Bob

  • Hosting company does not support SQL query with OUTFILE clause

    From my mysql database, I want to allow the user to run a query and produce a csv / text file of our membership database.   Unfortunately,  I just found out my hosting company does not support the SQL query with OUTFILE clause for MySQL database.
    Are there any other options available to produce a file besides me running the query in phpadmin and making the file available to users.
    Thanks.  George

    Maybe this external Export Mysql data to CSV - PHP tutorial will be of help
    Cheers,
    Günter

  • Left outer join 3 tables with where-statement

    Hi folks,
    I hope you can understand (and maybe solve) my problem.
    Generally I try to left outer join three tables. The third table is used for a WHERE-statement.
    The three table structures are the following:
    table 1 (user)   
    user1 | key
    table 2 (detail)  
    key | ID
    table 3 (header)
    ID | user2                 
    ...and I want to achieve the following structure (as example filled with data):
    user | key | ID
    |-----|----
    xy    | a    | 001
    xy    | b    | #
    z     | b     | #
    The clue ist the usage of the third table. I need the table to set user1 and user2 equal (WHERE) but there are two problems:
    1) Obviously I can't left outer join two tables with each other. In this case I already used the 'key' of table 1 to join it with the 'key' of table 2. So I can't left outer join the 'ID' of table 2 with the 'ID' of table 3. Error message that I can only left outer join a table once. Any proposals?
    2) I have to include a WHERE to equal user1 with user2. But I am not allowed to use the user2 from table 3 because of the left outer join.
    I tried this coding:
    SELECT auser1 akey b~id INTO TABLE itab FROM ( table1 AS a
      LEFT OUTER JOIN table2 AS b ON akey = bkey )
      LEFT OUTER JOIN table3 AS c ON bID = cID )
      WHERE auser1 = cuser2.
    I would really appreciate your help.
    Regards
    MrclSpdl

    IF you want to join a DB table with an internal table, you need to use the 'FOR ALL ENTRIES' statement.
    select dbfields
    into table itab2
    from dbtab
    for all entries in itab
    where dbfield1 = itab-field1.
    This will get you a second internal table with all the corresponding data for the first selection.  You can then join them with a loop through the first table and a read table on the second table (for 1 - 1 relation) or a nested loop statement on both tables (for 1 - N relation).  Make itab a hashed table when using read table with key, use a sorted table if you need to loop without key access.
    Regards,
    Freek

  • Hierarchical query with where clause

    Hi,
    How can I query hierarchically a query with WHERE clause? I have a table with three fields session_id,id and root_id.
    When I try with the following query,
    select id, level from relation
    where session_id = 79977
    connect by prior id = root_id start with id = 5042;
    It gets duplicate values.
    I want the query to show in the hierarchical manner with a filter condition using WHERE clause. Please help me how can I achieve this. If you know any link that describes more about this, please send it.
    Thanks in Advance.
    Regards,
    -Parmy

    Hi Sridhar Murthy an others,
    Thanks a lot for your/the answer. It's working for me. It saved a lot of other work around without the proper knowledge of hierarchical query. Please send me any link that describes these issues in detail and also I hope as I have mentioned in the other message, same cannot be achieved on views or ( on two different tables ???)
    Any way thanks for your reply,
    It's working for me.
    With happiness,
    -Parmy

  • Select query with UNION clause in database adapter

    Friends,
    I have got a SQL query with two UNION clause withing it. like
    select a,b,c
    from a
    union
    select a,b,c
    from b
    The schema generated is like below in sequence
    <element>a</element>
    <element>b</element>
    <element>c</element>
    <element>a</element>
    <element>b</element>
    <element>c</element>
    So, the columns from different select queries joined with UNION clause are all appeared in schema instead of the distinct columns.
    Is there any way around to solve this issue ? or will need to with DB function/procedure.

    I think I know what you are saying but your example doesn't make sense, your SQL should produce something like
    I had to change a, b, c with elementA, elementB, elementC as a and b are reserved html tags.
    <elementA>DateA</elementA>
    <elementB>DataB</elementB>
    <elementC>DataC</elementC>
    ...What is the result of the query when you run it in SQLPlus? Is it what you expect?
    cheers
    James

  • How to specify an outer join in query builder

    I've very quickly built a large query with the query builder, and it works fine, but only produces 9 out of 2200 records - so I need to change it to an outer join.
    My problem is that I can't seem to find a way to specify an outer join. I've tried editing the query that query builder formed, but it won't let me.
    I know I can capture the query, edit it and run it in sql developer, and that works fine, but I want to use query builder as it is the fastest way I know of to quickly add and remove items - my users are unsure of exactly what to include.
    I know it is kind of a trivial question, but i've searched the forum, the manual, the web and no luck
    Thanks for any help you can give
    Glenn

    Hi Glenn,
    When you use the Query Builder to create the sql statement, you should click on the empty square to the right of the fields on each table to create the join. When you've done this, you should see a line drawn between the two tables. Click on this line and a small popup appears allowing you to select inner, left outer or right outer joins.
    Once the report has been created, though, you need to edit the statement. For example, if you use the Query Builder to join DEPT to EMP based on the DEPTNO field on both tables, you get:
    select      "DEPT"."DEPTNO" as "DEPTNO",
          "DEPT"."DNAME" as "DNAME",
          "DEPT"."LOC" as "LOC",
          "EMP"."EMPNO" as "EMPNO",
          "EMP"."ENAME" as "ENAME",
          "EMP"."JOB" as "JOB",
          "EMP"."MGR" as "MGR",
          "EMP"."HIREDATE" as "HIREDATE"
    from      "EMP" "EMP",
          "DEPT" "DEPT"
    where   "DEPT"."DEPTNO"="EMP"."DEPTNO"Change this to:
    select      "DEPT"."DEPTNO" as "DEPTNO",
          "DEPT"."DNAME" as "DNAME",
          "DEPT"."LOC" as "LOC",
          "EMP"."EMPNO" as "EMPNO",
          "EMP"."ENAME" as "ENAME",
          "EMP"."JOB" as "JOB",
          "EMP"."MGR" as "MGR",
          "EMP"."HIREDATE" as "HIREDATE"
    from      "EMP" "EMP"
          LEFT OUTER JOIN "DEPT" "DEPT" ON "DEPT"."DEPTNO"="EMP"."DEPTNO"Andy

  • How to do outer join select query for an APEX report

    Hello everyone,
    I am Ann.
    I have one select statement that calculate the statistics for one month(October 2012 in this example)
    select ph.phase_number
    , sum ( (case
    WHEN ph.date_finished IS NULL OR ph.date_finished > last_day(TO_DATE('Oct 2012','MON YYYY'))
    THEN last_day(TO_DATE('Oct 2012','MON YYYY'))
    ELSE ph.date_finished
    END )
    - ph.date_started + 1) / count(def.def_id) as avg_days
    from phase_membership ph
    inner join court_engagement ce on ph.mpm_eng_id = ce.engagement_id
    inner join defendant def on ce.defendant_id = def.def_id
    where def.active = 1
    and ph.date_started <= last_day(TO_DATE('Oct 2012','MON YYYY'))
    and ph.active = 1
    and UPPER(ce.court_name) LIKE '%'
    group by rollup(phase_number)
    Result is as below
    Phase_Number     AVG_DAYS
    Phase One     8.6666666666666667
    Phase Two     14.6
    Phase Three     12
         11.4615365
    I have other select list mainly list the months between two date value.
    select to_char(which_month, 'MON YYYY') as display_month
    from (
    select add_months(to_date('Aug 2012','MON YYYY'), rownum-1) which_month
    from all_objects
    where
    rownum <= months_between(to_date('Oct 2012','MON YYYY'), add_months(to_date('Aug 2012','MON YYYY'), -1))
    order by which_month )
    Query result is as below
    DISPLAY_MONTH
    AUG 2012
    SEP 2012
    OCT 2012
    Is there any way that I can join these two select statement above to generate a result like:
    Month          Phase Number     Avg days
    Aug 2012     Phase One     8.666
    Sep 2012     Phase One     7.66
    Oct 2012     Phase One     5.66
    Aug 2012     Phase Two     8.666
    Sep 2012     Phase Two     7.66
    Oct 2012     Phase Two     5.66
    Aug 2012     Phase Three     8.666
    Sep 2012     Phase Three     7.66
    Oct 2012     Phase Three     5.66
    Or
    Month          Phase Number     Avg days
    Aug 2012     Phase One     8.666
    Aug 2012     Phase Two     7.66
    Aug 2012     Phase Three     5.66
    Sep 2012     Phase One     8.666
    Sep 2012     Phase Two     7.66
    Sep 2012     Phase Three     5.66
    Oct 2012     Phase One     8.666
    Oct 2012     Phase Two     7.66
    Oct 2012     Phase Three     5.66
    And it can be order by either Phase Number or Month.
    My other colleague suggest I should use an left outer join but after trying so many ways, I am still stuck.
    One of the select I tried is
    select a.display_month,b.* from (
    select to_char(which_month, 'MON YYYY') as display_month
    from (
    select add_months(to_date('Aug 2012','MON YYYY'), rownum-1) which_month
    from all_objects
    where
    rownum <= months_between(to_date('Oct 2012','MON YYYY'), add_months(to_date('Aug 2012','MON YYYY'), -1))
    order by which_month )) a left outer join
    ( select to_char(ph.date_finished,'MON YYYY') as join_month, ph.phase_number
    , sum ( (case
    WHEN ph.date_finished IS NULL OR ph.date_finished > last_day(TO_DATE(a.display_month,'MON YYYY'))
    THEN last_day(TO_DATE(a.display_month,'MON YYYY'))
    ELSE ph.date_finished
    END )
    - ph.date_started + 1) / count(def.def_id) as avg_days
    from phase_membership ph
    inner join court_engagement ce on ph.mpm_eng_id = ce.engagement_id
    inner join defendant def on ce.defendant_id = def.def_id
    where def.active = 1
    and ph.date_started <= last_day(TO_DATE(a.display_month,'MON YYYY'))
    and ph.active = 1
    and UPPER(ce.court_name) LIKE '%'
    group by to_char(ph.date_finished,'MON YYYY') , rollup(phase_number)) b
    on a.display_month = b.join_month
    but then I get an error
    SQL Error: ORA-00904: "A"."DISPLAY_MONTH": invalid identifier
    I need to display a report on APEX with option for people to download at least CSV format.
    I already have 1 inteactive report in the page, so don’t think can add another interactive report without using the iframe trick.
    If any of you have any ideas, please help.
    Thanks a lot.
    Ann

    First of all, a huge thanks for following this Frank.
    I have just started working here, I think the Oracle version is 11g, but not sure.
    To run Oracle APEX version 4, I think they must have at least 10g R2.
    This report is a bit challenging for me.I has never worked with PARTITION before.
    About the select query you suggested, I run , and it seems working fine, but if I try this,
    it return error ORA-01843: not a valid month
    DEFINE startmonth = "Aug 2012";
    DEFINE endmonth   = "Oct 2012";
    WITH     all_months     AS
         select add_months(to_date('&startmonth','MON YYYY'), rownum-1) AS which_month
         ,      add_months(to_date('&startmonth','MON YYYY'), rownum  ) AS next_month
         from all_objects
         where
         rownum <= months_between(to_date('&endmonth','MON YYYY'), add_months(to_date('&startmonth','MON YYYY'), -1))
    select TO_CHAR (am.which_month, 'Mon YYYY')     AS month
    ,      ph.phase_number
    , sum ( (case
    WHEN ph.date_finished IS NULL OR ph.date_finished > last_day(TO_DATE(am.which_month,'MON YYYY'))
    THEN last_day(TO_DATE(am.which_month,'MON YYYY'))
    ELSE ph.date_finished
    END )
    - ph.date_started + 1) / count(def.def_id) as avg_days
    FROM           all_months          am
    LEFT OUTER JOIN  phase_membership  ph  PARTITION BY (ph.phase_number)
                                        ON  am.which_month <= ph.date_started
                               AND am.next_month  >  ph.date_started
                               AND ph.date_started <= last_day(TO_DATE(am.which_month,'MON YYYY'))  -- May not be needed
                               AND ph.active = 1
    LEFT OUTER join  court_engagement  ce  on  ph.mpm_eng_id = ce.engagement_id
                                        and ce.court_name IS NOT NULL  -- or something involving LIKE
    LEFT OUTER join  defendant         def on  ce.defendant_id = def.def_id
                                        AND def.active = 1
    group by rollup(phase_number, am.which_month)
    ORDER BY  am.which_month
    ,            ph.phase_number
    ;Here is the shorted versions of the three tables:
    A_DEFENDANT, A_ENGAGEMENT, A_PHASE_MEMBERSHIP
    CREATE TABLE "A_DEFENDANT"
        "DEF_ID"     NUMBER NOT NULL ENABLE,
        "FIRST_NAME" VARCHAR2(50 BYTE),
        "SURNAME"    VARCHAR2(20 BYTE) NOT NULL ENABLE,
        "DOB" DATE NOT NULL ENABLE,
        "ACTIVE" NUMBER(2,0) DEFAULT 1 NOT NULL ENABLE,
        CONSTRAINT "A_DEFENDANT_PK" PRIMARY KEY ("DEF_ID"))
    Sample Data
    Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (101,'Joe','Bloggs',to_date('12/12/99','DD/MM/RR'),1);
    Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (102,'John','Smith',to_date('20/05/00','DD/MM/RR'),1);
    Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (103,'Jane','Black',to_date('15/02/98','DD/MM/RR'),1);
    Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (104,'Minnie','Mouse',to_date('13/12/88','DD/MM/RR'),0);
    Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (105,'Daisy','Duck',to_date('05/08/00','DD/MM/RR'),1);
    CREATE TABLE "A_ENGAGEMENT"
        "ENGAGEMENT_ID" NUMBER NOT NULL ENABLE,
        "COURT_NAME"    VARCHAR2(50 BYTE) NOT NULL ENABLE,
        "DATE_REFERRED" DATE,
        "DETERMINATION_HEARING_DATE" DATE,
        "DATE_JOINED_COURT" DATE,
        "DATE_TREATMENT_STARTED" DATE,
        "DATE_TERMINATED" DATE,
        "TERMINATION_TYPE" VARCHAR2(50 BYTE),
        "ACTIVE"           NUMBER(2,0) DEFAULT 1 NOT NULL ENABLE,
        "DEFENDANT_ID"     NUMBER,
        CONSTRAINT "A_ENGAGEMENT_PK" PRIMARY KEY ("ENGAGEMENT_ID"))
    Insert into A_ENGAGEMENT (ENGAGEMENT_ID,COURT_NAME,DATE_REFERRED,DETERMINATION_HEARING_DATE,DATE_JOINED_COURT,DATE_TREATMENT_STARTED,DATE_TERMINATED,TERMINATION_TYPE,ACTIVE,DEFENDANT_ID) values (1,'AA',to_date('12/08/12','DD/MM/RR'),null,to_date('12/08/12','DD/MM/RR'),null,null,null,1,101);
    Insert into A_ENGAGEMENT (ENGAGEMENT_ID,COURT_NAME,DATE_REFERRED,DETERMINATION_HEARING_DATE,DATE_JOINED_COURT,DATE_TREATMENT_STARTED,DATE_TERMINATED,TERMINATION_TYPE,ACTIVE,DEFENDANT_ID) values (2,'BB',to_date('01/09/12','DD/MM/RR'),null,to_date('02/09/12','DD/MM/RR'),null,null,null,1,102);
    Insert into A_ENGAGEMENT (ENGAGEMENT_ID,COURT_NAME,DATE_REFERRED,DETERMINATION_HEARING_DATE,DATE_JOINED_COURT,DATE_TREATMENT_STARTED,DATE_TERMINATED,TERMINATION_TYPE,ACTIVE,DEFENDANT_ID) values (3,'AA',to_date('02/09/12','DD/MM/RR'),null,to_date('15/09/12','DD/MM/RR'),null,null,null,1,103);
    Insert into A_ENGAGEMENT (ENGAGEMENT_ID,COURT_NAME,DATE_REFERRED,DETERMINATION_HEARING_DATE,DATE_JOINED_COURT,DATE_TREATMENT_STARTED,DATE_TERMINATED,TERMINATION_TYPE,ACTIVE,DEFENDANT_ID) values (4,'BB',to_date('01/10/12','DD/MM/RR'),null,to_date('02/10/12','DD/MM/RR'),null,null,null,1,105);
    CREATE TABLE "A_PHASE_MEMBERSHIP"
        "MPM_ID"       NUMBER NOT NULL ENABLE,
        "MPM_ENG_ID"   NUMBER NOT NULL ENABLE,
        "PHASE_NUMBER" VARCHAR2(50 BYTE),
        "DATE_STARTED" DATE NOT NULL ENABLE,
        "DATE_FINISHED" DATE,
        "NOTES"  VARCHAR2(2000 BYTE),
        "ACTIVE" NUMBER(2,0) DEFAULT 1 NOT NULL ENABLE,
        CONSTRAINT "A_PHASE_MEMBERSHIP_PK" PRIMARY KEY ("MPM_ID"))
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (1,1,'PHASE ONE',to_date('15/09/12','DD/MM/RR'),to_date('20/09/12','DD/MM/RR'),null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (2,1,'PHASE TWO',to_date('21/09/12','DD/MM/RR'),to_date('29/09/12','DD/MM/RR'),null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (3,2,'PHASE ONE',to_date('12/09/12','DD/MM/RR'),null,null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (4,3,'PHASE ONE',to_date('20/09/12','DD/MM/RR'),to_date('01/10/12','DD/MM/RR'),null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (5,3,'PHASE TWO',to_date('02/10/12','DD/MM/RR'),to_date('15/10/12','DD/MM/RR'),null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (6,4,'PHASE ONE',to_date('03/10/12','DD/MM/RR'),to_date('10/10/12','DD/MM/RR'),null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (7,3,'PHASE THREE',to_date('17/10/12','DD/MM/RR'),null,null,0);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (8,1,'PHASE THREE',to_date('30/09/12','DD/MM/RR'),to_date('16/10/12','DD/MM/RR'),null,1);
    The requirements are:
    The user must be able to request the extract for one or more calendar months, e.g.
    May 2013
    May 2013 – Sep 2013.
    The file must contain a separate row for each calendar month in the requested range. Each row must contain the statistics computed for that calendar month.
    The file must also include a row of totals.
    The user must be able to request the extract for either Waitakere or Auckland or Consolidated (both courts’ statistics accumulated).
    Then the part that I am stuck is
    For each monitoring phase:
    Phase name (e.g. “Phase One”)
    Avg_time_in_phase_all_particip
    for each phase name,
    Add up days in each “phase name” Monitoring Phase, calculated as:
    If Monitoring Phase.Date Finished is NULL or > month end date,
    +(*Month end date* Minus Monitoring Phase.Date Started Plus 1)+
    Otherwise (phase is complete)
    +(Monitoring Phase.Date Finished Minus Monitoring Phase.Date Started Plus 1.)+
    Divide by the numbers of all participants who have engaged in “phase name”.
    This is the words of the Business Analyst,
    I try to do as required but still struggle to identify end_month for the above formula to display for the range of months.
    Of course, I can write two nested cursor. The first one run the list of month, then for each month, run the parameterised report.
    But I prefer if possible just use SQL statements, or at least a PL/SQL but return a query.
    With this way, I can create an APEX report, and use their CSV Extract function.
    Yes, you are right, court_name is one of the selection parameters.
    And the statistics is not exactly for one month. It is kind of trying to identify all phases that are running through the specified month (even phase.date_started is before the month start).
    This is the reason why I put the condition AND ph.date_started <= last_day(TO_DATE('Oct 2012','MON YYYY')) (otherwise I get negative avg_days)
    User can choose either one court "AA" or "BB" or combined which is all figures.
    Sorry for bombarding you a lot of information.
    Thanks a lot, again.
    Edited by: Ann586341 on Oct 29, 2012 9:57 PM
    Edited by: Ann586341 on Oct 29, 2012 9:59 PM

  • Require a query with all clauses

    Hi All,
    I have been asked for a query to write by using all sql clauses like group by, where, having, order by in a single query. I just wrote the below query but I did not get out put. Please do correct where I am missing.
    select deptno, max(sal) from emp group by deptno having  deptno > ( select distinct deptno from emp where deptno >= 20)
    Thanks for your time and info.

    1007912 wrote:
    select deptno, max(sal) from emp group by deptno having  deptno > ( select distinct deptno from emp where deptno >= 20)
    Logically it was wrong; as your sub-query will return more then one record for comparison. By the way if you are querying the same data from same table then why you need a sub query in having clause! No need of it. Even if you are not using any aggregate predicates then use it with where clause.
    This is how your query and output should come out!
    SQL> select
      2   deptno, max(sal)
      3  from emp
      4  where deptno >= 20
      5  group by deptno
      6  order by 1
      7  /
        DEPTNO   MAX(SAL)
            20       3000
            30       2850
    SQL>

  • Outer join OJ syntax with JDBC drivers

    Hello,
    I'm facing a problem with CrystalReports 2008 and jdbc connection.
    Crystal genrates OJ syntax (as below) which cannot be interpreted by the Database.
    SELECT "T1"."T1D", "T2"."T2D", "T3"."T3D"
    FROM   {oj ("PUBLIC"."PUBLIC"."T3" "T3" LEFT OUTER JOIN "PUBLIC"."PUBLIC"."T2" "T2" ON "T3"."T2K"="T2"."T2K") LEFT OUTER JOIN "PUBLIC"."PUBLIC"."T1" "T1" ON "T2"."T1K"="T1"."T1K"}
    Prensently my database is HSQLDB.
    After browsing several post about ODBC, I tried to change the registry, introducing a new key
    HKEY_CURRENT_USER\Software\Business Objects\Suite 12.0\Crystal Reports\DatabaseOptions\NoOuterJoinEscSeq=myodbc3,hsqldb
    It did not change anything.
    Now, I suppose Crystal queries the database driver for its capabilities.
    This is done by a DatabaseMetaData object which implements several methods.
    In case of hsqldb, here is what the driver answers:
         public boolean supportsMinimumSQLGrammar() throws SQLException {
              return false;
         public boolean supportsCoreSQLGrammar() throws SQLException {
              return true;
         public boolean supportsExtendedSQLGrammar() throws SQLException {
              return false;
         public boolean supportsANSI92EntryLevelSQL() throws SQLException {
              return false;
         public boolean supportsANSI92IntermediateSQL() throws SQLException {
              return false;
         public boolean supportsANSI92FullSQL() throws SQLException {
              return false;
         public boolean supportsIntegrityEnhancementFacility() throws SQLException {
              return true;
         public boolean supportsOuterJoins() throws SQLException {
              return true;
         public boolean supportsFullOuterJoins() throws SQLException {
              return false;
         public boolean supportsLimitedOuterJoins() throws SQLException {
              return true;
    How can I tell Crystal to stop using the OJ syntax ?
    Thank you and kind regards.
    Alain

    Hi Alaine,
    You are correct, CR does query the driver to get what it requires to use for outer join syntax. The registry key will not work for this driver. It's the driver meta layer telling CR to use the oj syntax and is dependent on the driver being configured.
    Not sure if you can but start by trying to alter these settings if you can:
    public boolean supportsOuterJoins() throws SQLException {
    return true;
    public boolean supportsFullOuterJoins() throws SQLException {
    return false;
    I would think both should be reversed, true to false and false to true.
    Before you do that though go to our download page and install Service Pack 2, it may by a CR issue and the patch may have fixed the problem.
    If it doesn't I suggest asking this on the HSQLDB forum to see how to alter those option. CR follows the JDBC Type 4 Standards. You may want to see if Sun has a HSQLDB JDBC driver also.
    Thank you
    Don

  • Outer join two tables with two keys

    Hi,
    I have a question regard outer join,
    I have table A (Aid, ADesc), Table B(Bid, Bdesc), and Table C (Aid, Bid, Cdesc)
    There is data in Table A and B, but Table C is empty
    I want to outer join C with A and B with below query
    select ADesc,Bdesc, Cdest
    from A, B, C
    where A.Aid=C.Aid(+) and B.Bid(+)=C.Bid
    and A.Aid='XXX' and B.Bid(+)='ZZZ'
    The query result show only data in column Adesc , but column BDesc is empty even though there are some data in table B.
    How should the query been modified to correctly show ADESC and Bdesc.
    Thanks
    Vincent

    Guess the below should work:
    Case when records are available in Table C:
    with a as
    (select 'XXX' aid, 'adesc' adesc from dual),
    b as
    (select 'ZZZ' bid, 'bdesc' bdesc from dual),
    c as
    (select 'XXX' aid, 'ZZZ' bid, 'cdest' cdest from dual where 1 = 1)
    select ADesc,Bdesc, C1.Cdest
    from
    A LEFT OUTER JOIN C c1 ON (A.AID = C1.AID AND A.AID = 'XXX'),
    B LEFT OUTER JOIN C C2 ON (B.BID = C2.BID AND B.BID = 'ZZZ');
    Output:
    "ADESC"     "BDESC"     "CDEST"
    "adesc"     "bdesc"     "cdest"Case when table C is empty:
    with a as
    (select 'XXX' aid, 'adesc' adesc from dual),
    b as
    (select 'ZZZ' bid, 'bdesc' bdesc from dual),
    c as
    (select 'XXX' aid, 'ZZZ' bid, 'cdest' cdest from dual where 1 = 2)
    select ADesc,Bdesc, C1.Cdest
    from
    A LEFT OUTER JOIN C c1 ON (A.AID = C1.AID AND A.AID = 'XXX'),
    B LEFT OUTER JOIN C C2 ON (B.BID = C2.BID AND B.BID = 'ZZZ');
    "ADESC"     "BDESC"     "CDEST"
    "adesc"     "bdesc"     ""

  • Populate list by executing query with where clause

    Hi,
    I m populating my list from database table using following command.
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("learning", new HashMap());
    EntityManager em = emf.createEntityManager();
    String query = "select d from Dept d";
    List list = em.createQuery(query).getResultList();
    My list is getting populated with all of rows in my database table(dept). The problem is, I cant use where clause in my query string.
    String query = "select d from Dept d where d.dept_name='ANYNAME'";
    Moreover I cant select even indivisual columns by using following line
    String query = "select d.dept_code,d.dept_name from Dept d";
    It looks like that my query is getting all rows from table as Object.
    What to do to
    1. put some where clause
    2. get some particular colums instead of all columns
    3. apply some table joins in query
    plz help.

    Hi Alex,
    I misunderstood your question. You had mentioned "My list is getting populated with all of rows in my database table(dept). The problem is, I cant use where clause in my query string. "
    I thought you might not have permissions to modify the code in the class, and that's why I suggested that you could write new classes.
    1) write new classes,? means if I need just two columns from a table >(instead of all columns), do I need to write new class with just two >columns (getters and setters)?You can write a SQL statement anyway you want , there are no restrictions in JDBC , so if you need just 2 columns you can write a custom query for that.
    "select column1 as a, column2 as be from table_name where column3 = xyz" etc.
    2) Is not anyway to write SQL statement like
    select dept_code,dept_name from dept where dept_name='anything'The above SQL is correct, it should work.
    3) Stored procedures? can I get some example(code) to get an idea >how to implement complex queries with where clause and joinings >using stored procedures?Stored procedures are specific to the database you are using, Oracle has a particular syntax for store procdures.
    You can call stored procedures from JDBC also, search on Google for
    "Calling stored procedures from JDBC"
    4) I m using hibernate. can I get any example of using hibernate own >query?Tutorial on Hibernate Query Language:
    http://www.hibernate.org/hib_docs/v3/reference/en/html/queryhql.html

  • Issue in select query with where clause

    Hi guys,
    I'm facing an issue while using select query with the where clause. When I'm selecting all the data from the table it returns the correct result. But when I'm using the where clause to get the specific rows from the table it returns no rows. But the data I'm trying to fetch using the where condition exists in the table.
    Here is my query which causing the issue,
    select * from mytable where myfield = 'myvalue'
    But if I use the following query it returns the result correctly.
    select * from mytable
    Also the myfield value 'myvalue' exists in the table.
    I have tried by running this query in both SQL Developer and SQL Plus. I have tried this query in mssql as well. It works perfectly and returns correct result sets for both the queries I have mentioned above. I'm unable to predict the issue as I'm new to ORACLE. Please help.
    Thanks,
    Ram.

    Hi Ram,
    I experienced an issue similar to this with a varchar2 field. Some of our records had a hidden newline character at the end of them, which was making queries like the one below fail:
    select * from employees
    where email = '[email protected]'The best way I found to detect this was to use
    select 'XX'||email||'XX' from employeesTo make sure that there were no newlines. But that is just a guess. If you could provide some example table data and the outputs of your selects, it would be helpful.
    Jeff

  • Query with 'unique' clause

    Hi folks,
    A simple question (8.0.5 on WinNT):
    Is there any way to speed up the execution time for
    a query with a 'unique' clause? I have a table with 1.6 million
    records, and I want to get unique values for a
    particular column which is not the primary key.
    The result of the query -
    select unique(col1) from table1;
    typically returns between 1 to 100 unique values for col1.
    As such, this query takes upto 18 secs on my test machine in
    SQL Window itself (for 1.6 million records in the table). Any
    ways to speed it up?
    Thanks,
    Cheers,
    Sanchayan

    Having an index on the column should speed it up, but only
    where the column is defined as NOT NULL I think. If you
    can't put a NOT NULL constraint on the column consider
    whether you need to know about NULL values.
    If the index was of the bitmap type that would also speed it
    up further, probably to take the query time down to one or
    two seconds, but they come with a big list of warnings.
    Actually, I can't remember now if they're available in your
    version.

  • For Update Query with Wait Clause from ORACLE Forms

    Hi
    We are using Oracle Forms 10g running with 10g database 10.2.0.1.0. We happend to see a query which is getting generated in AWR report like Select rowid, all_columns from TableName for Update of C1 Nowait. But no such query is really written in forms and we are aware that, Any query prefixed with rowid is definitely executing from Forms. But how the ForUpdate and Nowait clause is appended to the query.
    We have checked the following properties in the database Block
    *1) Locking Mode is set to Automatic*
    *2) Update Changed Columns only is set to YES*
    *3) Query all records is set to No (Though this particular property may not be relevant to the issue)*
    What is the property or setting which might trigger such a query from ORACLE Forms with ForUpdate and Nowait clause.
    Any ideas/suggestions on why such behaviour. Please have a healthy discussion on this. Thanks in advance.

    Why have you started another thread on the same thing?
    FOR UPDATE cursor is causing Blocking/ Dead Locking issues
    Just use one thread to avoid confusion.
    The fact that nobody has answered on the other thread for a couple of days could be to do with it being the weekend and most people are not at work.
    Either be patient or, if it's more "urgent" than that, raise a SR/Tar with Oracle metalink.

Maybe you are looking for

  • Why won't my Itunes store display on screen?

    I have an old Mac OS X Version 10.6.8 I have been having a few issues recently, one of which is that when I try to open my Itunes store, this happens. Another is that my safari is old, and when I haven't been able to update as my version is too old t

  • Customer-Specific Key Figure and MCI3 analysis report

    Hi, We have created a "Customer-Specific Key Figures" in customizing and mapped the key with value category. But this new defined key figure is not available in the report MCI3. How to get this figure in the analysis report MCI3 etc , i.e. how to upd

  • Hr report categories.

    hi again All, I am facing a problem again. I tried generating a new category for my report. Now again after creating the category i do not see how to add fields and remove selection fields. I need only company code in my selection criteria and nothin

  • Can't set fsb clock (k7t266 pro )

    Hi there, I hope someone of you gurus is able and wanting to shed some light on my problem: I replaced the duron 700 on my k7t266 pro with a xp2000+ (palomino). When I want to change the fsb clock in the bios I can't. It stays 100Mhz I upgraded the b

  • How to gzip a file using java

    Friends, I want to gzip a file in unix using my java program, can I use Runtime.exec() method and run the gzip command to achieve this ? Is there any other way to zip/compress a file using java api ? Thanks