How to make outer join in Sub Query?

Hi!
I'm facing one problem. Can anyone tell me - how to make outer join in sub query?
I'm pasting one sample code -
select e.empno, e.ename,e.job,e.sal,d.deptno,d.dname
from d_emp e, d_dept d
where e.deptno(+) = (
                      case
                        when d_dept.deptno = 10
                          then
                              select deptno
                              from d_dept
                              where dname = 'SALES'
                      else
                        d_dept.deptno
                      end
SQL>
ERROR at line 15:
ORA-01799: a column may not be outer-joined to a subqueryHow to resolve this issue?
Regards.

And any luck with this?
SQL> with emp as
  2  (select 100 empno, 'Abcd' ename, 1000 sal, 10 deptno from dual
  3  union all
  4  select 101 empno, 'RRR' ename, 2000 sal, 20 deptno from dual
  5  union all
  6  select 102 empno, 'KKK' ename, 3000 sal, 30 deptno from dual
  7  union all
  8  select 103 empno, 'PPP' ename, 4000 sal, 10 deptno from dual
  9  )
10  ,dept as
11  (select 10 deptno, 'FINANCE' dname from dual
12  union all
13  select 20 deptno, 'SALES' dname from dual
14  union all
15  select 30 deptno, 'IT' dname from dual
16  union all
17  select 40 deptno, 'HR' dname from dual
18  )
19  select e.empno, e.ename, e.sal, d.deptno, d.dname
20  from emp e,
21       (select decode(a.deptno, 10, b.deptno, a.deptno) deptno, decode(a.deptno, 10, b.dname, a.dname) dname
22      from dept a, (select deptno, dname
23                    from dept
24                      where dname = 'SALES'
25                     ) b
26       ) d
27  where e.deptno(+) = d.deptno
28  /
     EMPNO ENAM        SAL     DEPTNO DNAME
       101 RRR        2000         20 SALES
       101 RRR        2000         20 SALES
       102 KKK        3000         30 IT
                                   40 HR
SQL> Cheers
Sarma.

Similar Messages

  • How to use outer join on this query?

    Hi all,
    Hope doing well,
    sir i am having one query which is here
    SELECT C.* ,
    P.Comp_Name Parent
    FROM Comp_Master C
    LEFT JOIN Comp_Master P
    ON C.Parent_ID = P.Comp_ID
    WHERE C.Comp_ID = 5;
    and here is my table Comp_Master data like this:
    Comp_ID Parent_ID Comp_Name
    5 1 abc123
    1 ROOT abc@123
    after running this query with all column value in parent column abc@123 value should come. but it's not happening.
    could u check this.
    if any query please let me know.
    Thanks

    p.s. when I run your query against your data....
    SQL> ed
    Wrote file afiedt.buf
      1  with comp_master as (select '5' comp_id, '1' parent_id, 'abc123' comp_name from dual union all
      2                       select '1' comp_id, 'ROOT' parent_id, 'abc@123' comp_name from dual
      3                      )
      4  --
      5  -- end of simulated table of test data
      6  --
      7  SELECT C.*
      8        ,P.Comp_Name Parent
      9  FROM Comp_Master C
    10       LEFT JOIN Comp_Master P ON C.Parent_ID = P.Comp_ID
    11* WHERE C.Comp_ID = 5
    SQL> /
    C PARE COMP_NA PARENT
    5 1    abc123  abc@123I get the output I expect from that query.
    So what are you expecting?
    I just ran the equivalent in SQL Server (I can't believe you got me to go and run that piece of rubbish... I haven't touched it in ages)...
    with comp_master as (select '5' comp_id, '1' parent_id, 'abc123' comp_name union all
                         select '1' comp_id, 'ROOT' parent_id, 'abc@123' comp_name
    SELECT C.*
          ,P.Comp_Name Parent
    FROM Comp_Master C
         LEFT JOIN Comp_Master P ON C.Parent_ID = P.Comp_ID
    WHERE C.Comp_ID = 5... and it gave me the same output.

  • How to use outer join condition in my below query.

    Hi All,
    How to use outer join condition in my below query.
    In the table  APPS_JP.GEDIS_OFFER_HEADER goh I have more records
    in the table APPS_JP.GEDIS_ORDER_BUILDS gob I have less number of records.
    I want all the records from APPS_JP.GEDIS_OFFER_HEADER goh
    including other conditions.
    I have tried goh.OFFER_NO=gob.OFFER_NO(+) but same result.
    [code]SELECT   GOH.ORIG_SYSTEM,
               gsp.USER_NAME,
               goh.ORDER_NO,
               goh.OMEGA_ORDER_NUMBER,
               goh.ORDER_TYPE,
               gc.CUSTOMER_ID,
               gc.OMEGA_CUSTOMER_NUMBER,
               CASE WHEN gc.PRIVATE = 'N' THEN gc.CUSTOMER_NAME ELSE '' END
                  AS COMPANY_NAME,
               goh.ORDER_STATUS,
               goh.TOTAL_SELLING_PRICE,
               goh.TOTAL_MARGIN,
                  ga1.ADDRESS1
               || ','
               || ga1.ADDRESS2
               || ','
               || ga1.ADDRESS3
               || ','
               || ga1.POSTAL_CODE
               || ','
               || ga1.CITY
                  AS SHIPPING_ADDRESS,
                  ga2.ADDRESS1
               || ','
               || ga2.ADDRESS2
               || ','
               || ga2.ADDRESS3
               || ','
               || ga2.POSTAL_CODE
               || ','
               || ga2.CITY
                  AS BILLING_ADDRESS,
               ga.ADDRESS_ID,
               gol.DESCRIPTION,
               APPS_JP.TZ.to_local_date (goh.OFFER_DATE, goh.OFFER_DATE_UTC)
                  AS OFFER_DATE,
               gc.LEVEL_8,
               goh.NO_OF_BUILDS,
               gob.SFDC_ID,
               goh.PURCHASE_ORDER_NO AS PO,
               gc1.CUSTOMER_NAME AS END_USAGE,
               gol.LOB,
               goh.TOTAL_MARGIN_PCT,
               goh.TOTAL_DISCOUNT,
               goh.TOTAL_DISCOUNT_PCT
        FROM   APPS_JP.GEDIS_OFFER_HEADER goh,
               APPS_JP.GEDIS_ORDER_BUILDS gob,
               APPS_JP.GEDIS_ORDER_LINES gol,
               APPS_JP.GEDIS_OFFER_RELATED_CUSTOMER gorc,
               APPS_JP.GEDIS_OFFER_RELATED_CUSTOMER ship,
               APPS_JP.GEDIS_OFFER_RELATED_CUSTOMER bill,
               APPS_JP.GEDIS_CUSTOMER gc,
               APPS_JP.GEDIS_CUSTOMER gc1,
               APPS_JP.GEDIS_CONTACT gct,
               APPS_JP.GEDIS_ADDRESS ga,
               APPS_JP.GEDIS_ADDRESS_NORM ga1,
               APPS_JP.GEDIS_ADDRESS_NORM ga2,
               (SELECT   DISTINCT SALESPERSON_ID, USER_NAME
                  FROM   APPS_JP.GEDIS_SALESPERSON
                 WHERE   SALESPERSON_ID IN
                               (SELECT   TO_NUMBER (COLUMN_VALUE) AS SALESPERSON_ID
                                  FROM   TABLE (APPS_GLOBAL.SplitString ('337309'))))
               gsp
       WHERE       goh.ORDER_NO <> 0
               AND goh.OFFER_NO <> 0
               AND goh.OFFER_NO=gol.OFFER_NO
               AND gol.BUILD_NO = 1
               AND gol.LINE_NO = 1
               AND goh.OFFER_NO=gob.OFFER_NO
               AND gob.BUILD_NO = 1
               AND goh.OFFER_NO = gorc.OFFER_NO
               AND gct.CONTACT_ID = gorc.CONTACT_ID
               AND ga.CUSTOMER_ID = gc.CUSTOMER_ID
               AND ga.PRIMARY = 'Y'
               AND goh.LEAD_SALESPERSON=gsp.SALESPERSON_ID
               AND goh.OFFER_NO = ship.OFFER_NO
               AND ship.RELATION_TYPE = 'SHIP'
               AND ga1.ADDRESS_ID = ship.ADDRESS_ID
               AND ga1.CUSTOMER_ID = gc1.CUSTOMER_ID
               AND goh.OFFER_NO = bill.OFFER_NO
               AND bill.RELATION_TYPE = 'BILL'
               AND ga2.ADDRESS_ID = bill.ADDRESS_ID
               AND goh.OFFER_DATE BETWEEN APPS_JP.TZ.LOCAL_TO_DB_DATE (
                                             SYSDATE - 30
                                      AND  APPS_JP.TZ.LOCAL_TO_DB_DATE (SYSDATE)
               AND gorc.RELATION_TYPE = 'BASE'
               AND gorc.CUSTOMER_ID = gc.CUSTOMER_ID
               AND goh.SALES_CHANNEL = gc.SALES_CHANNEL
               AND gc.SALES_CHANNEL = 'SMB'
               AND goh.LEAD_SALESPERSON IN (goh.CREATED_BY, goh.LEAD_SALESPERSON)
    ORDER BY   goh.OFFER_NO;[/code]
    Please help me how to use this outer join condition.
    Thanks in advance.

    Hi,
    If you want all the rows from goh, then you don't want any conditions like  goh.OFFER_NO <> 0.
    Make all the joins to goh outer joins, and make all conditions that apply to any tables joined to goh (or to tables joined to them) part of the join condition, like this:
    FROM             APPS_JP.GEDIS_OFFER_HEADER     goh
    LEFT OUTER JOIN  APPS_JP.GEDIS_ORDER_BUILDS     gob  ON   gob.OFFER_NO = goh.OFFER_NO
                                                         AND  gob.BUILD_NO = 1
    LEFT OUTER JOIN  APPS_JP.GEDIS_ORDER_LINES      gol  ON   gol.OFFER_NO = goh.OFFER_NO
                                                         AND  gol.BUILD_NO = 1
                                                         AND  gol.LINE_NO  = 1
    LEFT OUTER JOIN  APPS_JP.GEDIS_OFFER_RELATED_CUSTOMER
                                                    gorc ...
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
    Simplify the problem as much as possible.  For example, do you really need all those tables to show what the problem is?  Of course, you need them in tyour real query, but if you understand a solution that only involves 4 or 5 tables, you'll know how to apply it to any number of tables.
    Explain, using specific examples, how you get those results from that data.Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
    See the forum FAQ https://forums.oracle.com/message/9362002#9362002

  • Hi! Everyone, I have some problems with JOIN and Sub-query; Could you help me, Please?

    Dear Sir/Madam
    I'm a student who is interested in Oracle Database and
    I have some problems with JOIN and Sub-query.
    I hope so many of you could help me.
    if i use JOIN without sub-query, may it be faster or not?
    SELECT field1, field2 FROM tableA INNER JOIN tableB
    if i use JOIN with sub-query, may it be faster or not?
    SELECT field1,field2,field3 FROM tableA INNER JOIN (SELECT field1,field2 FROM tableB)
    Thanks in advance!

    Hi,
    fac30d8e-74d3-42aa-b643-e30a3780e00f wrote:
    Dear Sir/Madam
    I'm a student who is interested in Oracle Database and
    I have some problems with JOIN and Sub-query.
    I hope so many of you could help me.
    if i use JOIN without sub-query, may it be faster or not?
    SELECT field1, field2 FROM tableA INNER JOIN tableB
    if i use JOIN with sub-query, may it be faster or not?
    SELECT field1,field2,field3 FROM tableA INNER JOIN (SELECT field1,field2 FROM tableB)
    Thanks in advance!
    As the others have said, the execution plan will give you a better idea about which is faster.
    If you're trying to see how using (or not using) a sub-query affects performance, make the rest of the queries as similar as possible.  For example, include field3 in both queries, or ignore field3 in both queries.
    In this particular case, I guess the optimizer would do the same thing either way, but that's just a guess.  I can't see your execution plans.
    In general, simpler code is faster, and better in other ways, too.  In this case
    tableB
    is simpler than
    (SELECT field1, field2  FROM tableB)
    Why do you want a sub-query in this example?

  • Joining with sub query not working

    Hi
    I am new with these complex queries. I am trying to join a sub query to a query as below;
    SELECT Events1.InvoiceBatch AS BatchNo, Events1.InvoiceBatchDate AS BatchDate, tblClients.Company, tblClients.ID AS ClientID, COUNT(Events1.ID) AS Invoices,
    COUNT(*) - COUNT(Events1.InvoicePrintDate) AS E, Events1.InvoiceBatchFromDate AS BatchFrom, Events1.InvoiceBatchToDate AS BatchTo, (SELECT EventID, SUM(Total) FROM tblStaffBookings AS StaffBookings WHERE StaffBookings.EventID = Events1.ID GROUP BY EventID) AS Total
    FROM tblEvents AS Events1 LEFT OUTER JOIN
    tblClients ON Events1.ClientID = tblClients.ID
    WHERE (Events1.FactoringExportDate IS NULL) OR (Events1.AccountsExportDate IS NULL) OR (Events1.InvoiceSentDate IS NULL)
    GROUP BY Events1.InvoiceBatch, Events1.InvoiceBatchDate, tblClients.Company, tblClients.ID, Events1.InvoiceBatchFromDate, Events1.InvoiceBatchToDate
    HAVING (Events1.InvoiceBatch = 5212)
    ORDER BY tblClients.Company
    I am getting these two errors;
    Msg 8120, Level 16, State 1, Line 2
    Column 'tblEvents.ID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
    Msg 116, Level 16, State 1, Line 2
    Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
    What am I missing?
    Thanks
    Regards

    SELECT Events1.InvoiceBatch AS BatchNo, Events1.InvoiceBatchDate AS BatchDate, tblClients.Company, tblClients.ID AS ClientID, COUNT(Events1.ID) AS Invoices,
    COUNT(*) - COUNT(Events1.InvoicePrintDate) AS E, Events1.InvoiceBatchFromDate AS BatchFrom, Events1.InvoiceBatchToDate AS BatchTo,Total
    FROM tblEvents AS Events1 LEFT OUTER JOIN
    tblClients ON Events1.ClientID = tblClients.ID
    LEFT OUTER JOIN (SELECT EventID, SUM(Total) AS Total FROM tblStaffBookings AS StaffBookings WHERE StaffBookings.EventID = Events1.ID GROUP BY EventID) sb
    ON sb.EventID = Events1.ID
    WHERE (Events1.FactoringExportDate IS NULL) OR (Events1.AccountsExportDate IS NULL) OR (Events1.InvoiceSentDate IS NULL)
    GROUP BY Events1.InvoiceBatch, Events1.InvoiceBatchDate, tblClients.Company, tblClients.ID, Events1.InvoiceBatchFromDate, Events1.InvoiceBatchToDate,Total
    HAVING (Events1.InvoiceBatch = 5212)
    ORDER BY tblClients.Company
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page
    Says;
    Msg 4104, Level 16, State 1, Line 5
    The multi-part identifier "Events1.ID" could not be bound.
    on
    LEFT OUTER JOIN (SELECT EventID, SUM(Total) AS Total FROM tblStaffBookings AS StaffBookings WHERE StaffBookings.EventID = Events1.ID GROUP BY EventID) sb
    Regards

  • Outer Join with the query

    I have written the below query, our requirement is, Some employees have "Transport Allowance" but not "Project Allowance". For this, I tried to use OUTER JOIN with this query. But this query takes long time and failed. The following query works fine if the employee has both "Transport Allowance" and "Project Allowance" (without outer join) Now, I also need to retrieve the employees who have "Transport Allowance" but not "Project Allowance". How can I retrieve it?
    SELECT DISTINCT papf.employee_number
    , peev.screen_entry_value Transport_Allowance
    ,peev1.screen_entry_value Project_Allowance
    FROM apps.per_all_people_f papf
    ,apps.per_all_assignments_f paaf
    ,apps.pay_element_types_x petf
    ,apps.pay_element_types_x petf1
    ,apps.pay_element_types_x petf2
    ,apps.pay_element_entries_f peef
    ,apps.pay_element_entries_f peef1
    ,apps.pay_element_entries_f peef2
    ,apps.pay_element_entry_values_x peev
    ,apps.pay_element_entry_values_x peev1
    ,apps.pay_element_entry_values_x peev2
    ,apps.pay_input_values_x pivf
    ,apps.pay_input_values_x pivf1
    ,apps.pay_input_values_x pivf2
    WHERE
    papf.person_id = paaf.person_id
    AND paaf.assignment_id = peef.assignment_id
    AND paaf.assignment_id = peef1.assignment_id
    AND paaf.business_group_id = papf.business_group_id
    --Transport Allowance
    AND peef.element_entry_id = peev.element_entry_id
    AND petf.element_Name = 'Transport Allowance'
    AND pivf.element_type_id =petf.element_type_id
    AND pivf.name = 'Allowance'
    AND peev.input_value_id= pivf.input_value_id
    --Project Allowance
    AND peef1.element_entry_id = peev1.element_entry_id
    AND petf1.element_Name = "Project Allowance'
    AND pivf1.element_type_id = petf1.element_type_id
    AND pivf1.name = 'Allowance'
    AND peev1.input_value_id = pivf1.input_value_id
    AND (SYSDATE BETWEEN peev.effective_start_date AND peev.effective_end_date)
    AND (SYSDATE BETWEEN peev1.effective_start_date AND peev1.effective_end_date)
    AND (SYSDATE BETWEEN papf.effective_start_date AND papf.effective_end_date)
    ORDER BY papf.employee_number
    Thanks in advance.

    I am using sames tables with alias to retrieve the columns values from the same table.
    Here is my query.
    SELECT DISTINCT papf.employee_number
    , peev.screen_entry_value Transport_Allowance
    ,peev1.screen_entry_value Project_Allowance
    FROM apps.per_all_people_f papf
    ,apps.per_all_assignments_f paaf
    ,apps.pay_element_types_x petf
    ,apps.pay_element_types_x petf1
    ,apps.pay_element_entries_f peef
    ,apps.pay_element_entries_f peef1
    ,apps.pay_element_entry_values_x peev
    ,apps.pay_element_entry_values_x peev1
    ,apps.pay_input_values_x pivf
    ,apps.pay_input_values_x pivf1
    WHERE
    papf.person_id = paaf.person_id
    AND paaf.assignment_id = peef.assignment_id
    AND paaf.assignment_id = peef1.assignment_id
    AND paaf.business_group_id = papf.business_group_id
    --Transport Allowance
    AND peef.element_entry_id = peev.element_entry_id
    AND petf.element_Name = 'Transport Allowance'
    AND pivf.element_type_id =petf.element_type_id
    AND pivf.name = 'Allowance'
    AND peev.input_value_id= pivf.input_value_id
    --Project Allowance
    AND peef1.element_entry_id = peev1.element_entry_id
    AND petf1.element_Name = "Project Allowance'
    AND pivf1.element_type_id = petf1.element_type_id
    AND pivf1.name = 'Allowance'
    AND peev1.input_value_id = pivf1.input_value_id
    AND (SYSDATE BETWEEN peev.effective_start_date AND peev.effective_end_date)
    AND (SYSDATE BETWEEN peev1.effective_start_date AND peev1.effective_end_date)
    AND (SYSDATE BETWEEN papf.effective_start_date AND papf.effective_end_date)
    ORDER BY papf.employee_number
    Thanks in advance.

  • Restriction to Left Outer Joins in PS Query

    Hello I am trying to do Left Outer JOin in PS QUERY. I need to do dept tbl, job code tbl and locatable as left outer joins with JOB Table. Looks like in PS QUERY there is a error message saying as below. Can someone has any workaround to achieve this in PS QUERY. I know I can create a View and use that in PS QUERY but BUsiness Users are dependent on IT, so that doesn't work. Also, adding JOB table multiple times works but I am looking for better solution if anyone had come accorss working through PS QUERY Outer JOins.
    Windows Internet Explorer
    Left outer joins must be joined to the last record in the query. (139,290)
    OK
    Thanks,
    SC.

    Hi Mike,
    According to your description, you want to improve the performance for your DAX query in SQL Server Analysis Service Tabular model, right? Here is a white paper describes strategies and specific techniques for getting the best performance from your tabular
    models, including processing and partitioning strategies, DAX query tuning, and server tuning for specific workloads.
    http://msdn.microsoft.com/en-us/library/dn393915.aspx
    Since this is a complex DAX query, from a support perspective this is really beyond what we can do here in the forums. If you cannot determine your answer here or on your own, consider opening a support case with Microsoft. Visit this link to see the various
    support options that are available to better meet your needs:
    http://support.microsoft.com/default.aspx?id=fh;en-us;offerprophone
    Regards,
    Charlie Liao
    TechNet Community Support

  • How to make the text in sub-division

    Hi,
    I am usign text  module in my adobe forms.
    Text in text module contains sub-divisions as a), b) and c). Each sub-division are in a separate line.
    While in pdf, all the sub-division combines and comes a single paragraph.
    What  would be the problem for this issue? Any Idea?
    May I know how to make the text in sub-division as in text  module?
    Thanks,
    Thiyagu
    Edited by: Thiyagu on Oct 26, 2009 7:08 PM

    Hello, experiment with Object - Field tab. Do you have your text field with "allow multiple lines" checked? I guess so. And what about the field format? Plain text or Rich text? Please try:)) Regards, Otto

  • How to use outer join on 3 tables

    how to use outer join on 3 tables
    say tables are mkpf,lips and vbrp
    mkpf-xblnr = lips-vbeln
    lips-vbeln  = vbrp-vgbel

    refer following querry
        select a~bukrs
               a~anln1
               a~ord42
               a~ord43
               b~afabe
               b~ndabj
               b~kaafa
               b~aafag
               c~kostl
               d~afasl
               d~ndjar
               d~ndper
        into corresponding fields of table gt_master
        from ( ( anla as a inner join anlc as b
        on abukrs = bbukrs
        and aanln1 = banln1
        and aanln2 = banln2 )
        inner join anlz as c
        on  abukrs = cbukrs
        and aanln1 = canln1
        and aanln2 = canln2 )
        inner join anlb as d
        on  abukrs = dbukrs
        and aanln1 = danln1
        and aanln2 = danln2
        where a~bukrs in s_comp.

  • Can any one tell me how to make a join in between RESB & VBAP Table

    Hi.
    can any one tell me how to make a join in between RESB & VBAP Table. Please do the needful.

    u have Sales order number and sales order item number in RESB table..
    KDAUF   Sales Order Number
    KDPOS   Item Number in Sales Order

  • Client/server - how to make out

    In solaris how to make out weather the installed version is a client or Server..
    ??

    Hi,
    Earlier I had clint installed on my system. Now, I installed server as well on the system (for local testing purposes). Now when I look for what you said, OUI shows only server and when I look for directory I see
    1. C:\Program Files\Oracle\bin
    2. E:\oracle\product\10.2.0\db_1\BIN
    there is nothing like $ORACLE_HOME/bin/oracle
    Now how can I say what is what?
    OS Windows XP SP2
    Oracle 10gR2

  • 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

  • Outer join on aggregate query

    This is probably a relatively easy question as long as I explain it well enough:
    I have two tables:
    categorycodes and properties
    categorycodes is a lookup table.
    both tables have a field catcode that is a char(1) that contains matching data (only numbers 1 - 6)
    CREATE
      TABLE CATEGORYCODES
        CATCODE     CHAR(1 BYTE) NOT NULL ,
        DESCRIPTION VARCHAR2(25 BYTE) NOT NULL ,
        CONSTRAINT CATEGORYCODES_PK PRIMARY KEY ( CATCODE ) ENABLE
    catcode
    1
    2
    3
    4
    5
    6
    The properties table has about 600,000 records. The properties table also has a field called parcelno which is a char(9).  It contains a string of numbers and only numbers.
    What I'd like is the following:
    catcode, count(*)
    1   580
    2  300
    3 3000
    4 235
    5 0
    6 80
    I limited the query results to make sure that there was a set that would not have all the catcodes in it.  I am having trouble getting the one with zero to display.  I know this has to do with how I'm doing the join, but I'm not sure what.
    This is a sample of what I've tried:
    select i.*
    from
    (select catcode, count(*)
    from properties p
    where substr(parcelno,1,3) = '871'
    group by catcode) i
    right outer join categorycodes cc
    on i.catcode = cc.catcode;
    I am not worried about situations where catcode is null in properties.  Parcelno can never be null.

    Hi,
    It looks like your query should work; except you don't want to COUNT (*); that would make every number at least 1.  COUNT (*) means count the total number of rows, no matter what is on them, so it will see the row with just the catcode from the lookup table that doesn't match anything, and count that as 1.  You want to count the number of rows from the properties table, so count some column from the properties that can't be NULL.
    Here's a slightly different way
    SELECT    c.catcode
    ,         COUNT (p.catcode)     AS cnt
    FROM             categorycodes  c
    LEFT OUTER JOIN  properties     p  ON   p.catcode   = c.catcode
                                       AND  SUBSTR ( p.parcelno
                                                   , 1
                                                   , 3
                                                   )    = '871'
    If the condition about '871' is part of the join condition, then you don't need a sub-query.
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
    Point out where the statement above is getting the wrong results, and explain, using specific examples, how you get the right results from the given data in those places.
    Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002

  • How to use outer join to display the results

    I want to develop a report in which the column sequence will be as follows:
    1)Item_code
    2)Item_name
    3)Stock
    4)Pending
    5)Re-order Level
    6)Item_reorder_qty
    I had written the query, but the problem is all the products does not get displayed. The products are more than 700. But after running the query, only 364 gets displayed.
    How i can make use of outer join in the following statements :
    AND ITEM_CODE = LCS_ITEM_CODE
    AND ITEM_CODE = PI_ITEM_CODE
    AND LCS_ITEM_CODE = PI_ITEM_CODE
    in the below given query to solve this.
    SELECT
    ITEM_CODE,
    ITEM_NAME,
    ((LCS_STK_QTY_BU + LCS_RCVD_QTY_BU - LCS_ISSD_QTY_BU- LCS_REJECT_QTY_BU)/IU_MAX_LOOSE_1)STK ,
    SUM(TO_NUMBER(PI_QTY||'.'||PI_QTY_LS) - (PI_GI_QTY_BU/IU_CONV_FACTOR/IU_MAX_LOOSE_1))PNDG,
    ITEM_RORD_LVL,
    ITEM_RORD_QTY
    FROM
    OM_ITEM,
    OM_ITEM_UOM,
    OT_PO_HEAD,
    OT_PO_ITEM,
    OS_LOCN_CURR_STK
    WHERE (ITEM_UOM_CODE = IU_UOM_CODE AND ITEM_CODE = IU_ITEM_CODE)
    AND ITEM_CODE = LCS_ITEM_CODE
    AND ITEM_CODE = PI_ITEM_CODE
    AND LCS_ITEM_CODE = PI_ITEM_CODE
    AND LCS_LOCN_CODE ='RM'
    AND PI_PH_SYS_ID = PH_SYS_ID
    GROUP BY ITEM_CODE,ITEM_NAME,LCS_STK_QTY_BU,LCS_RCVD_QTY_BU,LCS_ISSD_QTY_BU,LCS_REJECT_QTY_BU,IU_MAX_LOOSE_1,ITEM_RORD_LVL,ITEM_RORD_QTY
    ORDER BY ITEM_CODE ASC
    Yogesh

    As you have no table aliases I can't tell what columns relate to which tables on your join conditions.
    Can you not just put (+) next to the outer joined columns you require on the where clause? Or perhaps consider using ANSI syntax for the joins such as <tableA> LEFT OUTER JOIN <tableB> ON (<join conditions>)

  • How to make Multiple parameters to sql query string seperated by ,(comma) ..

    Hi,
    I would like to konw how I can make multiple parameters to sql query string seperated by ,(comma)  ..
    For example, this parameters can be printed like 'abc,dde,ggf,eeg' ,once I use  "join(Parameters!rpCode.Value,",")" with report builder , 
    By the way, when I test this multiple parameters by Query Designer of report builder there was no problem,.(using Define query parameters, I put abc,dde,ggf,eeg)
    however, when I run this report , it won't be executing ,  with (rsErrorExecutingCommand)
    Plz, help me....

    If its sql query then it should like this
    Select t.*
    from table t
    inner join dbo.ParseValues(@Parameters,',')f
    on f.val = t.ID
    ParseValues can be found him
    http://visakhm.blogspot.in/2010/02/parsing-delimited-string.html
    or easier way is
    Select t.*
    from table t
    where ',' + @Parameters + ',' LIKE '%,' + CAST(t.ID AS varchar(10)) + ',%'
    Please Mark This As Answer if it solved your issue
    Please Mark This As Helpful if it helps to solve your issue
    Visakh
    My MSDN Page
    My Personal Blog
    My Facebook Page

Maybe you are looking for