Outer join vs. 'SELECT in SELECT'

Hi All,
I am generally curious about which method to use between a Outer join and 'SELECT in SELECT'. We can have same result with both methods.
My question is, for real life complex queries, which method is more efficiant? less resource intensive? Any thories you guys have?
I am on Oracle 10.2 on lunix.
See my example below
-- First table
create table emp
id   number,
name varchar2(1000),
constraint emp_pk primary key ( id )
-- second table. There will be 1 record, for few of the records in EMP table, in this table
create table leave
id     number,
emp_id number,
leave_date date,
constraint leave_pk primary key (id),
constraint leave_fk foreign key ( emp_id ) references emp
create index leave_idx_1 on leave ( emp_id ) ;
-- Populate some sample data in there
insert into emp (id, name)
select object_id, object_name from dba_objects where rownum < 10001 ;
declare
cursor c1 is
   select id from emp where mod(id,2) = 0 ;
v_id  number := 1 ;
v_date DATE := '01-JAN-08';
begin
  for c2 in c1
  loop
      insert into leave values ( v_id, c2.id, v_date );
      v_id := v_id + 1;
      v_date := v_date + 1;
  end loop;
end;
-- Set autotrace
set autotrace traceonly explain
-- =================================
-- Outer join
-- =================================
select e.id, e.name, l.id, l.leave_date
from   emp e, leave l
where  e.id = l.emp_id (+) ;
-- ===================================
-- select in select to get same results as above outer join
-- ===================================
select e.id, e.name,
       (select l.id from leave l where l.emp_id = e.id ) leave_id,
       (select l.leave_date from leave l where l.emp_id = e.id ) leave_date
from   emp e ;My hidden question, how these two methods internally work? in the plan we can only see something like 'hash join right outer' or something like that. But how exactly outer join is executed? how is the result formed?
I have got following plans for the two methods
SQL> select e.id, e.name, l.id, l.leave_date
  2  from   emp e, leave l
  3  where  e.id = l.emp_id (+) ;
Elapsed: 00:00:00.03
Execution Plan
Plan hash value: 98076489
| Id  | Operation             | Name  | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT      |       | 10000 |  5371K|    16   (7)| 00:00:01 |
|*  1 |  HASH JOIN RIGHT OUTER|       | 10000 |  5371K|    16   (7)| 00:00:01 |
|   2 |   TABLE ACCESS FULL   | LEAVE |  5012 |   171K|     6   (0)| 00:00:01 |
|   3 |   TABLE ACCESS FULL   | EMP   | 10000 |  5029K|     9   (0)| 00:00:01 |
Predicate Information (identified by operation id):
   1 - access("E"."ID"="L"."EMP_ID"(+))
Note
   - dynamic sampling used for this statement
SQL> select e.id, e.name,
  2         (select l.id from leave l where l.emp_id = e.id ) leave_id,
  3         (select l.leave_date from leave l where l.emp_id = e.id ) leave_date
  4  from   emp e ;
Elapsed: 00:00:00.18
Execution Plan
Plan hash value: 2670217481
| Id  | Operation                   | Name        | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT            |             | 10000 |  5029K|     9   (0)| 00:00:01 |
|   1 |  TABLE ACCESS BY INDEX ROWID| LEAVE       |    50 |  1300 |     2   (0)| 00:00:01 |
|*  2 |   INDEX RANGE SCAN          | LEAVE_IDX_1 |    20 |       |     1   (0)| 00:00:01 |
|   3 |  TABLE ACCESS BY INDEX ROWID| LEAVE       |    50 |  1100 |     2   (0)| 00:00:01 |
|*  4 |   INDEX RANGE SCAN          | LEAVE_IDX_1 |    20 |       |     1   (0)| 00:00:01 |
|   5 |  TABLE ACCESS FULL          | EMP         | 10000 |  5029K|     9   (0)| 00:00:01 |
Predicate Information (identified by operation id):
   2 - access("L"."EMP_ID"=:B1)
   4 - access("L"."EMP_ID"=:B1)
Note
   - dynamic sampling used for this statementPlease let me know your thoughts.
Thanks in advance

A better indicator of performance would be to look at the number of consistent gets that are required to execute the query.
In my environment:
SQL> SELECT * FROM V$VERSION;
BANNER
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
PL/SQL Release 10.2.0.4.0 - Production
CORE    10.2.0.4.0      Production
TNS for 64-bit Windows: Version 10.2.0.4.0 - Production
NLSRTL Version 10.2.0.4.0 - Production
SQL> SHOW PARAMETER OPT
NAME                                 TYPE        VALUE
filesystemio_options                 string
object_cache_optimal_size            integer     102400
optimizer_dynamic_sampling           integer     2
optimizer_features_enable            string      10.2.0.4
optimizer_index_caching              integer     0
optimizer_index_cost_adj             integer     100
optimizer_mode                       string      ALL_ROWS
optimizer_secure_view_merging        boolean     TRUE
plsql_optimize_level                 integer     2The OUTER JOIN produced the following results:
SQL> select e.id, e.name, l.id, l.leave_date
  2  from   emp e, leave l
  3  where  e.id = l.emp_id (+) ;
10000 rows selected.
Execution Plan
Plan hash value: 98076489
| Id  | Operation             | Name  | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT      |       | 10000 |   380K|     9  (12)| 00:00:01 |
|*  1 |  HASH JOIN RIGHT OUTER|       | 10000 |   380K|     9  (12)| 00:00:01 |
|   2 |   TABLE ACCESS FULL   | LEAVE |  5017 | 80272 |     3   (0)| 00:00:01 |
|   3 |   TABLE ACCESS FULL   | EMP   | 10000 |   224K|     5   (0)| 00:00:01 |
Predicate Information (identified by operation id):
   1 - access("E"."ID"="L"."EMP_ID"(+))
Statistics
          0  recursive calls
          0  db block gets
        723  consistent gets
          0  physical reads
          0  redo size
     364047  bytes sent via SQL*Net to client
       7672  bytes received via SQL*Net from client
        668  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
      10000  rows processedThe inline subquery produced these results:
SQL> select e.id, e.name,
  2         (select l.id from leave l where l.emp_id = e.id ) leave_id,
  3         (select l.leave_date from leave l where l.emp_id = e.id ) leave_dat
  4  from   emp e ;
10000 rows selected.
Execution Plan
Plan hash value: 1706216391
| Id  | Operation         | Name  | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT  |       | 10000 |   224K|     5   (0)| 00:00:01 |
|*  1 |  TABLE ACCESS FULL| LEAVE |     1 |     9 |     3   (0)| 00:00:01 |
|*  2 |  TABLE ACCESS FULL| LEAVE |     1 |    13 |     3   (0)| 00:00:01 |
|   3 |  TABLE ACCESS FULL| EMP   | 10000 |   224K|     5   (0)| 00:00:01 |
Predicate Information (identified by operation id):
   1 - filter("L"."EMP_ID"=:B1)
   2 - filter("L"."EMP_ID"=:B1)
Statistics
          0  recursive calls
          0  db block gets
     360705  consistent gets
          0  physical reads
          0  redo size
     364053  bytes sent via SQL*Net to client
       7672  bytes received via SQL*Net from client
        668  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
      10000  rows processedSee the 723 consistent gets versus 360705? That is a huge difference.
The second method may be more viable if you create indexes on the columns in the leave table that you are joining to your EMP table.
For example:
SQL> CREATE INDEX LEAD_ID_IDX ON LEAVE(EMP_ID, ID, LEAVE_DATE);
Index created.
SQL> set autotrace traceonly
SQL> select e.id, e.name,
  2         (select l.id from leave l where l.emp_id = e.id ) leave_id,
  3         (select l.leave_date from leave l where l.emp_id = e.id ) leave_date
  4  from   emp e ;
10000 rows selected.
Execution Plan
Plan hash value: 1822800249
| Id  | Operation         | Name        | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT  |             | 10000 |   224K|     5   (0)| 00:00:01 |
|*  1 |  INDEX RANGE SCAN | LEAD_ID_IDX |     1 |     9 |     2   (0)| 00:00:01 |
|*  2 |  INDEX RANGE SCAN | LEAD_ID_IDX |     1 |    13 |     2   (0)| 00:00:01 |
|   3 |  TABLE ACCESS FULL| EMP         | 10000 |   224K|     5   (0)| 00:00:01 |
Predicate Information (identified by operation id):
   1 - access("L"."EMP_ID"=:B1)
   2 - access("L"."EMP_ID"=:B1)
Statistics
          1  recursive calls
          0  db block gets
      22111  consistent gets
         19  physical reads
          0  redo size
     364053  bytes sent via SQL*Net to client
       7672  bytes received via SQL*Net from client
        668  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
      10000  rows processedThe query improved by a more than a factor of 10 with the index but the consistent gets are still significantly higher then the OUTER JOIN query. Additionally I always try and take the approach when developing queries to minimize the number of table accesses possible. In your second place you have to access the LEAVE table twice, instead of once in the first query.

Similar Messages

  • ORA-30563, Outer Join not allowed in select list

    I can not find any information about this error message that I am getting.
    I have just upgraded my Oracle database from Version 7.3 to Version 8.1.7, a stored procedure that was written in v7.3 has outer joins in the select statement.
    when trying to run this proc in version 8 I get this meesage.(ORA-30563, Outer Join not allowed in select list)
    code ex:
    Select alt.id
    decode(alt.advise, NULL, NULL, AA.act_yr(+))||'-'||AA.act_per(+)||'-'||AA.Acc_per_no(+)) as advise_no
    from alt, AA;
    Is there any information about this message anywhere? or does anybody know if this is a known issue with oracle ver 8.1.7?
    Thanks
    CJ

    It appears to have been a bug in 7.x
    From a metalink note on bugs fixed in 8i (doc 132632.1)
    974742 Oracle does not report an error if (+) is specified in select-list. The OUTER JOIN operator (+) is only valid in WHERE clause predicates. As this is not flagged as an error the query can give unexpected results. The correct action to avoid this problem is to fix the query.
    Ken

  • Outer join in view criteria: how to ?

    Hello,
    I have to create a VO for a LOV. I created in this VO a ViewCriteria to pass variables for the query.
    The problem is that for one of this variable I have to set the clause as an outer join.
    JDeveloper creates:
    SELECT MyView1.Item, MyView2.Code
    FROM MyView1, MyView2
    WHERE MyView1.ID = MyView2.EXT_ID (+)
    AND MyView1.Item = :TheItem
    AND MyView2.Code = :TheCodebut I need something like:
    SELECT MyView1.Item, MyView2.Code
    FROM MyView1, MyView2
    WHERE MyView1.ID = MyView2.EXT_ID (+)
    AND MyView1.Item = :TheItem
    AND :TheCode = MyView2.Code (+)

    ADFboy wrote:
    this is optional parameter value, in the view criteria windows is this option....
    AdfBoyNo, this parameter is not optional because, in the call of the LOV it will be always set.
    But the query without the outer join returns too few rows...
    I tried to find where to "intercept" this programmatically, but I'm failing doing this. :(
    I'll have the same problem with another field, not for a LOV but to get the value of an attribute of a VO.
    Even in advanced mode the Where clause can't have parameters...

  • Issues with limit/filter on outer join table in BQY

    I'm converting a series of BQY's from Brio 6.6 to Hyperion 9.3. I have some questions about the "use ODBC outer join syntax on limits" option in the OCE. I sort of understand this option's purpose, but I don't completely understand the SQL I'm seeing. For example Brio 6.6 is generating the following SQL statement:
    SELECT * FROM tblA AL1 LEFT OUTER JOIN tblB AL38 ON (AL38.ParentID=AL1.ChildID AND
    AL38.Data='SomeData') WHERE ((NOT AL38.Action IS NULL))
    Now, Hyperion 9.3 generated the SQL statement as follows:
    SELECT * FROM tblA AL1 LEFT OUTER JOIN tblB AL38 ON (AL38.ParentID=AL1.ChildID AND
    AL38.Data='SomeData') AND (NOT AL38.Response IS NULL))
    My questions are:
    1) Why isn't the "NOT AL38.Action IS NULL" statement included in the outer join in Brio? My limited understanding of the "use ODBC outer join syntax on limits" seems to indicate that it should end up there. I want the SQL to look like this, but I don't know why Brio generates this SQL.
    2) How can I get Hyperion to generate the same SQL as Brio? And still use the OCE with "use ODBC outer join syntax on limits" selected?

    Setting the Cardinality of Department > Employee role to OptionalOne
    gives rise to cartesian join (which is a bigger issue).
    Therefore, the Cardinality of Department > Employee role should remain as
    OptionalMany (default).
    This means, the outer join problem still remains unsolved. I have, therefore,
    unmarked the above answer by me.
    The question is - why has Report Builder been designed in such a way that the primary entity is always the child entity when attributes are selected from both parent and child entities?
    Most people desire that all the rows of the parent entity be fetched irrespective of whether there are corresponding rows in the child entity or not. Report Builder tool should not dictate what the user wants to get, meaning it is not right to assume
    that the focus of the report is Employee when attributes are selected from both Department and Employee. Report Builder should not make the child entity (i.e., Employee) as the primary entity when the user selects attributes from the child entity after
    having selected attributes from the parent entity.
    I am sorry to say that clients may not accept the Report Builder tool as this does not fetch the records as desired.
    I hope there is someone who can suggest how the outer join problem can be solved by just tweaking the properties of the report model (SMDL).
    Besides, the end users are business users and are not tech savvy. They are not expected to modify queries. They would simply drag and drop attributes from entities to create adhoc reports.

  • Full outer join query giving error

    Hi I have written the below query to get the fields below as an out put but am getting the error missing keyword..am not understanding where did i missed..i have done step by step query analysis..but could not find the error.
    Please help me in resolving the issue.
    Expected output Columns :*
    COUNTRY , TRN_TYPE ,SKU ,BIX_Customer ,PERIOD ,CURRENTSTOCK ,STOCK_VALUE ,SALES ,SALES_VALUE ,TARGET
    Query :_
    select (case when a.country is null then b.country when b.country is null then c.country else a.country end) AS COUNTRY,
    (case when a.Sale_Type is null then b.Stk_type when b.stk_type is null then c.Stk_type else a.Sale_Type end) AS TRN_TYPE,
    (case when a.sku is null then b.sku when b.sku is null then c.sku else a.sku end) AS SKU,
    (case when a.bix_customer is null then b.bix_customer_code when b.bix_customer_code is null then c.bix_customer_code else a.bix_customer end)AS BIX_Customer ,
    (case when a.period is null then TO_number(b.period) when b.period is null then TO_NUMBER(c.period) else a.period end) AS PERIOD,
    nvl(b.CURRENTSTOCK,0) AS CURRENTSTOCK,
    nvl(b.stock_value,0) AS STOCK_VALUE,
    nvl(a.sales,0) AS SALES,
    nvl(a.SALES_VALUE,0) AS SALES_VALUE,
    nvl(c.TARGET_QTY,0) AS TARGET
    from
    (select UPPER(c.cust_country_name) AS COUNTRY,
    DECODE(ds.account_key,7156,'SAMPLE',7157,'BONUS',7485,'SALE') AS Sale_Type,
    substr(i.item_code,7) AS SKU,
    c.bix_customer_code AS BIX_Customer,
    ds.descr as descr ,
    ds.period as period,
    sum(ds.quantity) AS SALES,
    sum(case when ds.local_value is null then ds.euro_value else ds.local_value END) AS SALES_VALUE
    FROM distributor_sales ds, customer c, item i
    where ds.customer_key=c.customer_key
    and ds.item_key= i.item_key
    group by ds.period,
    ds.account_key,
    c.cust_country_name,
    substr(i.item_code,7),
    c.bix_customer_code,
    ds.descr) a
    full outer join
    (SELECT UPPER(b.cust_country_name) AS COUNTRY,
    DECODE(s.stock_type,'SALE','SALE','SALES','SALE','BONUS','BONUS','SAMPLE','SAMPLE') AS Stk_type,
    substr(c.item_code,7) AS SKU,
    s.descr as descr,
    s.period as period,
    b.bix_customer_code,
    sum(s.CLOSING_STOCK) CURRENTSTOCK,
    sum(s.closing_stock*s.cif_price) STOCK_VALUE
    FROM STOCK s, customer b, item c
    WHERE s.customer_key=b.customer_key
    and s.item_key= c.item_key
    group by
    s.descr,
    s.stock_type,
    s.period, b.bix_customer_code,b.cust_country_name,substr(c.item_code,7) ) b
    full outer join
    (SELECT UPPER(cu.cust_country_name) AS COUNTRY,
    DECODE(t.description,'SALES TARGET','SALE') AS Stk_type,
    substr(it.item_code,7) AS SKU,
    t.channel as channel,
    t.period as period,
    cu.bix_customer_code as bix_customer_code,
    sum(t.quantity) TARGET_QTY
    FROM sales_target t, customer cu, item it
    WHERE t.customer_key=cu.customer_key
    and t.item_key= it.item_key
    group by
    t.channel,
    t.description,
    t.period, cu.bix_customer_code,cu.cust_country_name,substr(it.item_code,7) ) c
    on a.SKU=b.SKU
    and a.sku=c.SKU
    and b.sku=c.SKU
    and a.BIX_Customer=b.bix_customer_code
    and a.BIX_Customer=c.bix_customer_code
    and b.bix_customer_code=c.bix_customer_code
    and a.Sale_Type=b.Stk_type
    and a.Sale_Type=c.Stk_type
    and b.Stk_type=c.Stk_type
    and a.descr=b.descr
    and b.descr=c.channel
    and a.descr=c.channel
    and a.country=b.country
    and a.country=c.COUNTRY
    and b.country=c.COUNTRY
    and a.period=b.period
    and a.period=c.period
    and b.period=c.period;

    <tt>Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production</tt>
    You must be aware that you must cascade full outer joins
    with
    t1 as
    (select 1 key,1.1 data from dual union all
    select 3,1.3 from dual union all
    select 6,1.6 from dual union all
    select 7,1.7 from dual
    t2 as
    (select 2 key,2.2 data from dual union all
    select 3,2.3 from dual union all
    select 4,2.4 from dual union all
    select 6,2.6 from dual
    t3 as
    (select 4 key,3.4 data from dual union all
    select 5,3.5 from dual union all
    select 6,3.6 from dual union all
    select 7,3.7 from dual
    select nvl(x.key,t3.key) key,
           x.data_1,
           x.data_2,
           t3.data data_3
      from (select nvl(t1.key,t2.key) key,
                   t1.data data_1,
                   t2.data data_2
              from t1
                   full outer join
                   t2
                on t1.key = t2.key
           ) x
           full outer join
           t3
        on t3.key = x.key
    order by keyunless you can live with duplicate key rows you cannot avoid whenever all table pairs contain common keys (try the below using data from above)
    select coalesce(t1.key,t2.key,t3.key) key,
           t1.data data_1,
           t2.data data_2,
           t3.data data_3
      from t1
           full outer join
           t2
        on t1.key = t2.key
           full outer join
           t3
        on t3.key = t1.key
       and t3.key = t2.key
    order by key
    select coalesce(t1.key,t2.key,t3.key) key,
           t1.data data_1,
           t2.data data_2,
           t3.data data_3
      from t2
           full outer join
           t3
        on t2.key = t3.key
           full outer join
           t1
        on t1.key = t2.key
       and t1.key = t3.key
    order by key
    select coalesce(t1.key,t2.key,t3.key) key,
           t1.data data_1,
           t2.data data_2,
           t3.data data_3
      from t1
           full outer join
           t3
        on t1.key = t3.key
           full outer join
           t2
        on t2.key = t1.key
       and t2.key = t3.key
    order by keyRegards
    Etbin
    Edited by: Etbin on 10.4.2013 9:53
    If you're after
    select *
      from (select *
              from (select *
                      from t1
                   ) a
                   full outer join
                   (select *
                      from t2
                   ) b
                on t1.key = t2.key
           ) x
           full outer join
           t3
        on t3.key = x.key
    order by keyyou're presently at
    select *
      from (
                   (select *
                      from t1
                   ) a
                   full outer join
                   (select *
                      from t2
                   ) b
                on t1.key = t2.key
           ) x
           full outer join
           t3
        on t3.key = x.key
    order by keyORA-00933: SQL command not properly ended

  • How to achieve outer join operator(+) in HQL?

    Dear all,
    The two tables employee and customer have not explicate association (by FK and PK). In Oracle SQL, we can use the operator (+) as follows for an outer join. For example,
    SELECT * FROM  employee, customer           where employee.name = customer.name(+)
    However, HQL does not support this outer join operator. How can we translate the above SQL select to HQL?
    Regards.
    Pengyou

    shashi_rajak wrote:
    Already posted in [ hibernate forum|https://forum.hibernate.org/viewtopic.php?f=1&t=997869] . This does not have to do with java.
    Yes, but I did not get any solution.
    Hibernate has something to do with java. You can not say for example java has nothing to do with Internet or Internet has nothing to do with Computer. Anyhow, thanks for your reply.

  • Outer join with effective date in peoplesoft query

    Hi,
    I'm trying to join two tables using outer join. Both tables are effective dated:
    Dept_Tbl: dept_id, status, effdt
    Tips_Tbl: dept_id, tips_id, effdt
    Not all records in Dept_Tbl are in Tips_Tbl. I need to get all active depts and their most recent tips_id if they have one.
    select a.dept_id, b.tips_id
    from dept_tbl a, tips_tbl b
    where a.status = 'Active'
    and a.effdt =
    (select max(a_ed.effdt) from dept_tbl a_ed
    where a.dept_id = a_ed.dept_id
    and a_ed.effdt <= SYSDATE)
    and b.dept_id(+) = a.dept_id
    and b.effdt =
    (select max(b_ed.effdt) from tips_tbl b_ed
    where b.dept_id = b_ed.dept_id
    and b.tips_id = b_ed.tips_id
    and b_ed.effdt <= SYSDATE)
    The query only returns records that are in both tables.
    Is there a way for outer join to work with effective dates?
    Thanks in advance,
    Reg

    Here is an example of one solution. Note the use of NVL on both sides of the equal sign since both sides could be NULL in the case of the outer join
    with dept_tbl as (select 1 dept_id, SYSDATE effdt FROM DUAL),
         tips_tbl as (select 1 dept_id, NULL effdt FROM DUAL)
    select a.effdt
      from dept_tbl a,
           tips_tbl b
    where b.dept_id(+) = a.dept_id
       and NVL(b.effdt, SYSDATE) = NVL((select max(b_ed.effdt)
                                          from tips_tbl b_ed
                                         where b.dept_id = b_ed.dept_id
                                           and b_ed.effdt <= SYSDATE), SYSDATE);
    EFFDT
    5/7/2007 3:25:00 PM

  • "use ODBC outer join syntax on limits"  issues

    I'm converting a series of BQY's from Brio 6.6 to Hyperion 9.3. I have some questions about the "use ODBC outer join syntax on limits" option in the OCE. I sort of understand this option's purpose, but I don't completely understand the SQL I'm seeing. For example Brio 6.6 is generating the following SQL statement:
    SELECT * FROM tblA AL1 LEFT OUTER JOIN tblB AL38 ON (AL38.ParentID=AL1.ChildID AND
    AL38.Data='SomeData') WHERE ((NOT AL38.Action IS NULL))
    Now, Hyperion 9.3 generated the SQL statement as follows:
    SELECT * FROM tblA AL1 LEFT OUTER JOIN tblB AL38 ON (AL38.ParentID=AL1.ChildID AND
    AL38.Data='SomeData') AND (NOT AL38.Response IS NULL))
    My questions are:
    1) Why isn't the "NOT AL38.Action IS NULL" statement included in the outer join in Brio? I'm OK with the fact that it is not, but my limited understanding of the "use ODBC outer join syntax on limits" seems to indicate that it should end up there.
    2) The Hyperion SQL is returning incorrect results. How can I get Hyperion to generate the same SQL as Brio? And still use the OCE with "use ODBC outer join syntax on limits" selected? This setting is working fine for other BQY's.

    In the first post, I modified the actual table name I'm using, the following is my actual output:
    SQL> SELECT A0.name partName,A2.name usedPartName FROM WTPartUsageLink A1
    2 RIGHT OUTER JOIN (
    3 (SELECT A0.idA2A2,A0B.name FROM WTPart A0 INNER JOIN WTPartMaster A0B
    4 ON ((A0.idA3masterReference = A0B.idA2A2)))
    5 UNION ALL
    6 (SELECT A0.idA2A2,A0B.name
    7 FROM WTProduct A0 INNER JOIN WTProductMaster A0B ON ((A0.idA3masterRefer
    ence = A0B.idA2A2)))) A0
    8 ON (A0.idA2A2 = A1.idA3A5) LEFT OUTER JOIN
    9 (SELECT A2.idA2A2,A2.name FROM WTPartMaster A2
    10 UNION ALL
    11 SELECT A2.idA2A2,A2.name FROM WTProductMaster A2) A2
    12 ON (A1.idA3B5 = A2.idA2A2) ORDER BY partName DESC,usedPartName DESC;
    FROM WTProduct A0 INNER JOIN WTProductMaster A0B ON ((A0.idA3masterRefer
    ence = A0B.idA2A2)))) A0
    ERROR at line 7:
    ORA-00923: FROM keyword not found where expected
    SQL> select * from v$version;
    BANNER
    Oracle9i Enterprise Edition Release 9.2.0.1.0 - 64bit Production
    PL/SQL Release 9.2.0.1.0 - Production
    CORE 9.2.0.1.0 Production
    TNS for Solaris: Version 9.2.0.1.0 - Production
    NLSRTL Version 9.2.0.1.0 - Production
    Thanks,

  • 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

  • Oute Join and Inner Join

    Hi,
    I need to join three tables, based on some conditions (EKPO, EKBE and EKKN Note: All PO line items from EKPO will have a movement associated in the EKBE Table. Capture all PO line items where no matches found in the EKPO-EKBE join)
    for the above requirement shall I write my query like this?
    SELECT ekpo~ebeln
             ekpo~ebelp
             ekpo~loekz
             ekpo~txz01
             ekpo~matnr
             ekpo~bukrs
             ekpo~werks
             ekpo~menge
             ekpo~meins
             ekpo~knttp
             ekbe~vgabe
             ekbe~bwart
             ekbe~menge
             ekbe~dmbtr
             ekbe~shkzg
             ekkn~sakto
             ekkn~kostl
             ekkn~ps_psp_pnr
    INTO CORRESPONDING FIELDS OF TABLE i_podata
             FROM ekpo LEFT OUTER JOIN ekbe ON ekbeebeln = ekpoebeln AND
                                               ekbeebelp = ekpoebelp
                            INNER JOIN ekkn ON ekknebeln = ekpoebeln AND
                                               ekknebelp = ekpoebelp
                                         WHERE ekpo~werks IN s_werks AND
                                               ekpo~ebeln IN s_ebeln.
    Shall I use both Outer Join and Inner join in one Query?
    Please correcte me.
    Thanks
    Frank Rex

    Hi,
    You can use both inner join and outer join in the same select statement.
    Ensure first all the inner joins between tables are declared and put the left outer join at the end.
    Some sample code for your reference:
      SELECT
              AVBELN AKUNNR ABSTNK ABSTDK AVKORG AVTWEG AAUART AKNUMV
              BPOSNR BMATNR BWERKS BSPART BLGORT BKZWI1
              SUM( BKWMENG ) AS KWMENG DBZIRK D~VKGRP
              EDISPO EPRCTR
    FROM VBAK AS A INNER JOIN VBAP AS B ON AVBELN EQ BVBELN
                   INNER JOIN VBPA AS C ON CVBELN EQ BVBELN
                   INNER JOIN KNVV AS D ON DKUNNR EQ AKUNNR
                AND DVKORG EQ AVKORG AND DVTWEG EQ AVTWEG
                   LEFT OUTER JOIN MARC AS E ON E~MATNR EQ
                             BMATNR AND EWERKS EQ B~WERKS
              INTO CORRESPONDING FIELDS OF TABLE IT_ORDERS
              WHERE A~VKORG IN SO_VKORG
              AND A~VTWEG IN SO_VTWEG
              AND A~KUNNR IN SO_KUNNR
              AND A~ERDAT IN SO_ERDAT
              AND A~AUART IN ('ZFOR','ZROR','ZEOR','ZDXR','ZXOR','ZRM1','ZGOR','ZSOR')
              AND B~MATNR IN SO_MATNR
              AND B~WERKS IN SO_WERKS
              AND B~SPART IN SO_SPART
              AND B~ABGRU EQ SPACE
              AND A~LIFSK EQ SPACE
              AND A~FAKSK EQ SPACE
              AND B~VSTEL IN SO_VSTEL
              AND B~LGORT IN SO_LGORT
              AND C~KUNNR IN SO_SHIP
              AND C~PARVW EQ 'WE'
              AND D~VKGRP IN SO_VKGRP
              AND D~BZIRK IN SO_BZIRK
              AND B~LGORT NE '0950'
              GROUP BY AVBELN AKUNNR ABSTNK ABSTDK 
              AVKORG AVTWEG AAUART AKNUMV B~POSNR
              BMATNR BWERKS BSPART BKZWI1 D~BZIRK
              DVKGRP BLGORT EDISPO EPRCTR E~MATGR.
    Lakshminarayanan.
    P.S.Mark all helpful answers for points.

  • Alternative to Outer Join

    Hi,
    I am using outer join in the below SQL, It returns all the rows from Table A and only the matching data from Table B,
    for the unmatching rows, we get NULL values. It is clear, is it possible to achieve the same without applying
    outer joins in anyway, please clarify.
    select a.*, b.*
    from a left outer join b
    on a.f1 = b.f1

    Karthick_Arp wrote:
    An outer join query like this
    select e.empno, d.deptno
    from emp e
    left join dept d
    on e.deptno = d.deptnocan also be writern like this
    select e.empno, (select d.deptno from dept d where d.deptno = e.deptno) deptno
    from emp eBut if you can join them just join. There are exceptions as well when Scalar Subquery can be usefull. Here is a nice post in Asktom.
    http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1594885400346999596
    Edited by: Karthick_Arp on Aug 14, 2009 12:01 AMOne should note that the two statements only deliver the identical result because d.deptno is unique.
    The same does not work when you join to non unique columns.

  • How can I crate a view with tables which require "Left outer join"?

    Hi guys,
    how can I define a view with tables which require "Left outer join"?. In SE11 "View",->tab "Join condition", it seems that it valid only for "Inner Join".
    Please give me some hint.
    Thanks in advance.
    Regards,
    Liying

    Hi
    Inner Join and Outer Join 
    The data that can be selected with a view depends primarily on whether the view implements an inner join or an outer join.
    With an inner join, you only get the records of the cross-product for which there is an entry in all tables used in the view.
    With an outer join, records are also selected for which there is no entry in some of the tables used in the view. (ABAP allows left outer join.)
    The data that can be selected with a view depends primarily on whether the view implements an inner join or an outer join.

  • BLS - Full Outer Join

    What would cause a JOIN action block to fail when I try to do a FULL OUTER JOIN?  The join works when I select an inner join or an outer join.  If I select full outer join, I get the error:
    [ERROR]: Joiner: Index: 14, Size: 14
    [ERROR]: ACTION FAILED: End Action Join_Open : (Joiner)
    Thanks

    What version/build are you using?
    Regards,
    Jamie

  • Dynamic From statement in select query and/or outer join not working

    Dear Experts, I have a select query where the select columns are dynamic, the where condition is also dynamic. It is of the below format:
    Select (dynamic columns) INTO <wa>
    FROM a inner join b on af1 = bf1
    inner join c on af2 = cf2......
    WHERE (dynamic conditios)
    ORDER BY ( dynamic sort condition).
    Now I have to include some tables (dynamically depending on the user input) in the inner join statement which will give description for the selected fields. And these database tables may or may no be empty. So in this case, my select query will not return any data if these tables are empty. And I dont want that.
    I tried using outer join for the extra tables but it gave me a runtime error. I also tried forming the inner join statement dynamically but it was not supporting.
    Kindly give me pointers.
    Thanks

    Hey thanks for the reply, but the problem is not solved.
    I am already using  ( fileds, value) like table in my where condition and the select statement was working properly.
    the problem is that now I have to include some tables in the join statement which can be empty and so i want to use Outer join.
    But I am getting a runtime error as below:
    Error analysis
        An exception occurred that is explained in detail below.
        The exception, which is assigned to class 'CX_SY_DYNAMIC_OSQL_SYNTAX', was not
         caught in
        procedure "ZATSCSNG_RFC_READ_TABLE" "(FUNCTION)", nor was it propagated by a
         RAISING clause.
        Since the caller of the procedure could not have anticipated that the
        exception would occur, the current program is terminated.
        The reason for the exception is:
        The running ABAP program wanted to execute a SELECT statement whose
        WHERE condition was (partly) specified dynamically. The part that is
        specified in an internal table at runtime is compared to a field of the
        right table of an LEFT OUTER JOIN. Such comparisons are not supported by
         all database systems and are therefore not allowed.

  • SQL Select using LEFT OUTER JOIN returning field values when I expect NULL

    I am having problems with this select statement:
    SELECT distinct pl.id, th.trip, pc.country, pph.location
    FROM people_list pl, people_travelhistory th, people_country pc
    LEFT OUTER JOIN people_info pph on pph.id=pl.id and pph.country=pc.country
    where people_list.active='Y' and people_list.id=th.id and th.trip = pc.trip;
    The criteria is that the pph table may not have no record for that id and country.
    The problem is that the pph.location field is returned with data even when no matching record for that id or country exists.
    If the record doesn't exist in the pph table, I want pph.location = NULL
    What am I doing wrong?
    Thanks in Advance!
    Developer

    Hi, You can try this :
    SELECT distinct pl.id, th.trip, pc.country, pph.location
    FROM people_list pl, people_travelhistory th, people_country pc
    left outer join people_info pph on pph.id = pl.id
    left outer join people_country pc on pc.country = pph.country
    left outer join people_travelhistory th on th.id = pl.id
    where pl.active='Y' and th.trip = pc.trip;
    Knowing that you requesting people active that have travelled to their own country.
    Regards

  • 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

Maybe you are looking for