SQL query problem - select max (case... aggregate function)

Hi,
I have a problem with below sql query, it gives me problem/error message 'ORA-00937: not a single-group group function', why?
select sag.afdeling, sag.sagsnr, to_char(sag.start_dato, 'yyyy-mm-dd'), sag.stat, BOGF_TRANS.TRANSTYPE,
max (case when BOGF_TRANS.TRANSTYPE = 'K' then sum(bogf_trans.belobdkk) end) + -- as "TRANSTYPE K",
max (case when BOGF_TRANS.TRANSTYPE = 'D' then sum(bogf_trans.belobdkk) end) as "TRANSTYPE K & D",
max (case when BOGF_TRANS.TRANSTYPE = 'S' then sum(bogf_trans.belobdkk) end) as "SUM TRANSTYPE S"
from sag
join bogf_trans on sag.selskab = bogf_trans.selskab and sag.sagsnr = bogf_trans.sagsnr and sag.afdeling = bogf_trans.afdeling
where SAG.SELSKAB=37 and SAG.AFDELING = 'SUS' AND SAG.SAGSNR = 10876
group by sag.afdeling, sag.sagsnr, sag.start_dato, sag.stat, BOGF_TRANS.TRANSTYPE
If I exclude (columns) as below it give me correct summations (max (case... sum(...)) but then I miss some important info that I need
select
max (case when BOGF_TRANS.TRANSTYPE = 'K' then sum(bogf_trans.belobdkk) end) + -- as "TRANSTYPE K",
max (case when BOGF_TRANS.TRANSTYPE = 'D' then sum(bogf_trans.belobdkk) end) as "TRANSTYPE K & D",
max (case when BOGF_TRANS.TRANSTYPE = 'S' then sum(bogf_trans.belobdkk) end) as "SUM TRANSTYPE S"
from sag
join bogf_trans on sag.selskab = bogf_trans.selskab and sag.sagsnr = bogf_trans.sagsnr and sag.afdeling = bogf_trans.afdeling
where SAG.SELSKAB=37 and SAG.AFDELING = 'SUS' AND SAG.SAGSNR = 10876
group by sag.afdeling, sag.sagsnr, sag.start_dato, sag.stat, BOGF_TRANS.TRANSTYPE
Any ideas?

Moved to more sutable forum, sorry.

Similar Messages

  • SQL query using Group by and Aggregate function

    Hi All,
    I need your help in writing an SQL query to achieve the following.
    Scenario:
    I have table with 3 Columns. There are 3 possible values for col3 - Success, Failure & Error.
    Now I need a query which can give me the summary counts for distinct values of col3 for each GROUP BY of col1 and col2 values. When there are no values for col3 then it should return ZERO count.
    Example Data:
    Col1 Col2 Col3
    abc 01 success
    abc 02 success
    abc 01 success
    abc 01 Failure
    abc 01 Error
    abc 02 Failure
    abc 03 Error
    xyz 07 Failure
    Required Output:
    c1 c2 s_cnt F_cnt E_cnt (Heading)
    abc 01 2 1 1
    abc 02 1 1 0
    abc 03 0 0 1
    xyz 07 0 1 0
    s_cnt = Success count; F_cnt = Failure count; E_cnt = Error count
    Please note that the output should have 5 columns with col1, col2, group by (col1,col2)count(success), group by (col1,col2)count(failure), group by (col1,col2)count(error)
    and where ever there are NO ROWS then it should return ZERO.
    Thanks in advance.
    Regards,
    Shiva

    Hi,
    user13015050 wrote:
    Thanks TTT. Unfortunately I cannot use this solution because I have huge data for this.T's solution is basically the same as mine. The first 23 lines just simulates your table. Since you actually have a table, you would start with T's line 24:
    SELECT col1 c1, col2 c2, SUM(decode(col3, 'success', 1, 0)) s_cnt, ...
    user13015050 wrote:Thanks a lot Frank. It helped me out. I just did some changes to this as below and have no issues.
    SELECT     col1
    ,     col2
    ,     COUNT ( CASE
              WHEN col3 = 'SUCCESS'
              THEN 1
              END
         )          AS s_cnt
    ,     COUNT ( CASE
              WHEN col3 = 'FAILED'
              THEN 1
              END
         )          AS f_cnt
    ,     COUNT ( CASE
              WHEN col3 = 'ERROR'
              THEN 1
              END
         )          AS e_cnt
    FROM     t1
    WHERE c2 in ('PURCHASE','REFUND')
    and c4 between to_date('20091031000000','YYYYMMDDHH24MISS') AND to_date('20100131235959','YYYYMMDDHH24MISS')
    GROUP BY c1, c2
    ORDER BY c1, c2;
    Please let me know if you see any issues in this query.It's very hard to read.
    This site normally compresses spaces. Whenever you post formatted text (such as queries or results) on this site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
    Also, post exactly what you're using.  The code above is SELECTing col1 and col2, but there's no mention of either in the GROUP BY clause, so I don't believe it's really what you're using.
    Other than that, I don't see anything wrong or suspicious in the query.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Error while executing a sql query for select

    HI All,
    ORA-01652: unable to extend temp segment by 128 in tablespace PSTEMP i'm getting this error while i'm executing the sql query for selecting the data.

    I am having 44GB of temp space, while executing the below query my temp space is getting full, Expert please let us know how the issue can be resolved..
    1. I dont want to increase the temp space
    2. I need to tune the query, please provide your recomendations.
    insert /*+APPEND*/ into CST_DSA.HIERARCHY_MISMATCHES
    (REPORT_NUM,REPORT_TYPE,REPORT_DESC,GAP,CARRIED_ITEMS,CARRIED_ITEM_TYPE,NO_OF_ROUTE_OF_CARRIED_ITEM,CARRIED_ITEM_ROUTE_NO,CARRIER_ITEMS,CARRIER_ITEM_TYPE,CARRIED_ITEM_PROTECTION_TYPE,SOURCE_SYSTEM)
    select
    REPORTNUMBER,REPORTTYPE,REPORTDESCRIPTION ,NULL,
    carried_items,carried_item_type,no_of_route_of_carried_item,carried_item_route_no,carrier_items,
    carrier_item_type,carried_item_protection_type,'PACS'
    from
    (select distinct
    c.REPORTNUMBER,c.REPORTTYPE,c.REPORTDESCRIPTION ,NULL,
    a.carried_items,a.carried_item_type,a.no_of_route_of_carried_item,a.carried_item_route_no,a.carrier_items,
    a.carrier_item_type,a.carried_item_protection_type,'PACS'
    from CST_ASIR.HIERARCHY_asir a,CST_DSA.M_PB_CIRCUIT_ROUTING b ,CST_DSA.REPORT_METADATA c
    where a.carrier_item_type in('Connection') and a.carried_item_type in('Service')
    AND a.carrier_items=b.mux
    and c.REPORTNUMBER=(case
    when a.carrier_item_type in ('ServicePackage','Service','Connection') then 10
    else 20
    end)
    and a.carrier_items not in (select carried_items from CST_ASIR.HIERARCHY_asir where carried_item_type in('Connection') ))A
    where not exists
    (select *
    from CST_DSA.HIERARCHY_MISMATCHES B where
    A.REPORTNUMBER=B.REPORT_NUM and
    A.REPORTTYPE=B.REPORT_TYPE and
    A.REPORTDESCRIPTION=B.REPORT_DESC and
    A.CARRIED_ITEMS=B.CARRIED_ITEMS and
    A.CARRIED_ITEM_TYPE=B.CARRIED_ITEM_TYPE and
    A.NO_OF_ROUTE_OF_CARRIED_ITEM=B.NO_OF_ROUTE_OF_CARRIED_ITEM and
    A.CARRIED_ITEM_ROUTE_NO=B.CARRIED_ITEM_ROUTE_NO and
    A.CARRIER_ITEMS=B.CARRIER_ITEMS and
    A.CARRIER_ITEM_TYPE=B.CARRIER_ITEM_TYPE and
    A.CARRIED_ITEM_PROTECTION_TYPE=B.CARRIED_ITEM_PROTECTION_TYPE
    AND B.SOURCE_SYSTEM='PACS'
    Explain Plan
    ==========
    Plan
    INSERT STATEMENT ALL_ROWSCost: 129 Bytes: 1,103 Cardinality: 1                                                        
         20 LOAD AS SELECT CST_DSA.HIERARCHY_MISMATCHES                                                   
              19 PX COORDINATOR                                              
                   18 PX SEND QC (RANDOM) PARALLEL_TO_SERIAL SYS.:TQ10002 :Q1002Cost: 129 Bytes: 1,103 Cardinality: 1                                         
                        17 NESTED LOOPS PARALLEL_COMBINED_WITH_PARENT :Q1002Cost: 129 Bytes: 1,103 Cardinality: 1                                    
                             15 HASH JOIN RIGHT ANTI NA PARALLEL_COMBINED_WITH_PARENT :Q1002Cost: 129 Bytes: 1,098 Cardinality: 1                               
                                  4 PX RECEIVE PARALLEL_COMBINED_WITH_PARENT :Q1002Cost: 63 Bytes: 359,283 Cardinality: 15,621                          
                                       3 PX SEND BROADCAST PARALLEL_TO_PARALLEL SYS.:TQ10001 :Q1001Cost: 63 Bytes: 359,283 Cardinality: 15,621                     
                                            2 PX BLOCK ITERATOR PARALLEL_COMBINED_WITH_CHILD :Q1001Cost: 63 Bytes: 359,283 Cardinality: 15,621                
                                                 1 MAT_VIEW ACCESS FULL MAT_VIEW PARALLEL_COMBINED_WITH_PARENT CST_ASIR.HIERARCHY :Q1001Cost: 63 Bytes: 359,283 Cardinality: 15,621           
                                  14 NESTED LOOPS ANTI PARALLEL_COMBINED_WITH_PARENT :Q1002Cost: 65 Bytes: 40,256,600 Cardinality: 37,448                          
                                       11 HASH JOIN PARALLEL_COMBINED_WITH_PARENT :Q1002Cost: 65 Bytes: 6,366,160 Cardinality: 37,448                     
                                            8 BUFFER SORT PARALLEL_COMBINED_WITH_CHILD :Q1002               
                                                 7 PX RECEIVE PARALLEL_COMBINED_WITH_PARENT :Q1002Cost: 1 Bytes: 214 Cardinality: 2           
                                                      6 PX SEND BROADCAST PARALLEL_FROM_SERIAL SYS.:TQ10000 Cost: 1 Bytes: 214 Cardinality: 2      
                                                           5 INDEX FULL SCAN INDEX CST_DSA.IDX$$_06EF0005 Cost: 1 Bytes: 214 Cardinality: 2
                                            10 PX BLOCK ITERATOR PARALLEL_COMBINED_WITH_CHILD :Q1002Cost: 63 Bytes: 2,359,224 Cardinality: 37,448                
                                                 9 MAT_VIEW ACCESS FULL MAT_VIEW PARALLEL_COMBINED_WITH_PARENT CST_ASIR.HIERARCHY :Q1002Cost: 63 Bytes: 2,359,224 Cardinality: 37,448           
                                       13 TABLE ACCESS BY INDEX ROWID TABLE PARALLEL_COMBINED_WITH_PARENT CST_DSA.HIERARCHY_MISMATCHES :Q1002Cost: 0 Bytes: 905 Cardinality: 1                     
                                            12 INDEX RANGE SCAN INDEX PARALLEL_COMBINED_WITH_PARENT SYS.HIERARCHY_MISMATCHES_IDX3 :Q1002Cost: 0 Cardinality: 1                
                             16 INDEX RANGE SCAN INDEX PARALLEL_COMBINED_WITH_PARENT CST_DSA.IDX$$_06EF0001 :Q1002Cost: 1 Bytes: 5 Cardinality: 1

  • PL/SQL function body returning SQL Query Problem

    I have wandered around the forums and found quite a bit of helpful information that has gotten me to the point I am now at. Unfortuntely, PL/SQL is not my strongest point and I am getting an error when I attempt to run my report.
    This is what I have for my package:
    CREATE OR REPLACE PACKAGE LIB2.report_query
    is
    function create_report2(v1 IN varchar2) RETURN VARCHAR2;
    end report_query;
    CREATE OR REPLACE PACKAGE BODY LIB2.report_query
    as
    function create_report2(v1 in varchar2) return varchar2
    is
    l_vc_format HTMLDB_APPLICATION_GLOBAL.VC_ARR2 := HTMLDB_UTIL.STRING_TO_TABLE(v1);
    l_format varchar2(255) := HTMLDB_UTIL.TABLE_TO_STRING(l_vc_format);
    q1 varchar2(32767) := ' ';
    begin
    q1 :=
    'select b.BOOK_ID, bk.book_id bkid, bkk.book_id bkkid, b.TITLE, b.SUBTITLE, b.SERIES, b.VOLUME, b.ISBN, f.FORMAT_RET, b.DESCRIPTION, .PUBLISHED,'
    ||'b.PURCHASED_FROM, b.COMMENTS, b.WEBSITE, c.LENGTH_MINS, stragg(p.last_name || '', '' || p.first_name) Author, '
    ||'stragg(p.person_id) person_id, '
    ||'pb.name PUBLISHER, decode(b.abridged, ''Y'',''Abridged'',''N'',''Unabridged'') Abridged,'
    ||'(nvl(d.disk01,0)+nvl(d.disk02,0)+nvl(d.disk03,0)+nvl(d.disk04,0)+nvl(d.disk05,0)+nvl(d.disk06,0)+nvl(d.disk07,0)+nvl(d.disk08,0)+'
    ||'nvl(d.disk09,0)+nvl(d.disk10,0)+nvl(d.disk11,0)+nvl(d.disk12,0)+nvl(d.disk13,0)+nvl(d.disk14,0)+nvl(d.disk15,0)+nvl(d.disk16,0)+nvl(d.disk17,0)+'
    ||'nvl(d.disk18,0)+nvl(d.disk19,0)+nvl(d.disk20,0)+nvl(d.disk21,0)+nvl(d.disk22,0)+nvl(d.disk23,0)+nvl(d.disk24,0)+nvl(d.disk25,0)+nvl(d.disk26,0)+'
    ||'nvl(d.disk27,0)+nvl(d.disk28,0)+nvl(d.disk29,0)+nvl(d.disk30,0)+nvl(d.disk31,0)+nvl(d.disk32,0)+nvl(d.disk33,0)+nvl(d.disk34,0)+nvl(d.disk35,0)+'
    ||'nvl(d.disk36,0)+nvl(d.disk37,0)+nvl(d.disk38,0)+nvl(d.disk39,0)+nvl(d.disk40,0)+nvl(d.disk41,0)+nvl(d.disk42,0)+nvl(d.disk43,0)+nvl(d.disk44,0)+'
    ||'nvl(d.disk45,0)+nvl(d.disk46,0)+nvl(d.disk47,0)+nvl(d.disk48,0)+nvl(d.disk49,0)+nvl(d.disk50,0)) total_tracks'
    ||'from book b, '
    ||'book bk,'
    ||'book bkk,'
    ||'person p,'
    ||'lkup_book_author la,'
    ||'lkup_book_publisher lp,'
    ||'lkup_book_format lkf,'
    ||'format f,'
    ||'publisher pb,'
    ||'conversion_info_audio c,'
    ||'lkup_book_disk_info d'
    ||'where b.book_id = la.book_id'
    ||'and b.book_id = bk.book_id'
    ||'and b.book_id = bkk.book_id'
    ||'and p.person_id = la.author_id'
    ||'and b.book_id = lp.book_id'
    ||'and b.book_id = c.book_id'
    ||'and b.book_id = d.book_id'
    ||'and b.book_id = lkf.book_id'
    ||'and lkf.format_id = f.format_id'
    ||'and pb.publisher_id(+) = lp.publisher_id'
    ||'and b.wishlist = ''N'''
    ||'and (upper(b.book_id) like ''%'' || upper(:P40_SEARCH) || ''%'''
    ||'or upper(b.title) like ''%'' || upper(:P40_SEARCH) || ''%'''
    ||'or upper(b.subtitle) like ''%'' || upper(:P40_SEARCH) || ''%'''
    ||'or upper(b.series) like ''%'' || upper(:P40_SEARCH) || ''%'''
    ||'or upper(b.volume) like ''%'' || upper(:P40_SEARCH) || ''%'''
    ||'or upper(b.isbn) like ''%'' || upper(:P40_SEARCH) || ''%'''
    ||'or upper(b.format) like ''%'' || upper(:P40_SEARCH) || ''%'''
    ||'or upper(b.description) like ''%'' || upper(:P40_SEARCH) || ''%'''
    ||'or upper(b.published) like ''%'' || upper(:P40_SEARCH) || ''%'''
    ||'or upper(b.purchased_from) like ''%'' || upper(:P40_SEARCH) || ''%'''
    ||'or upper(b.comments) like ''%'' || upper(:P40_SEARCH) || ''%'''
    ||'or upper(b.website) like ''%'' || upper(:P40_SEARCH) || ''%'''
    ||'or upper(p.last_name) like ''%'' || upper(:P40_SEARCH) || ''%'''
    ||'or upper(p.first_name) like ''%'' || upper(:P40_SEARCH) || ''%'''
    ||'or upper(pb.name) like ''%'' || upper(:P40_SEARCH) || ''%'''
    ||'or upper(:P40_SEARCH) is null)'
    ||'and ((upper(b.title) like ''%'' || upper(:P40_TITLE) || ''%'' or upper(:P40_TITLE) is null))'
    ||'and ((upper(b.series) like ''%'' || upper(:P40_SERIES) || ''%'' or upper(:P40_SERIES) is null))'
    ||'and ((upper(p.last_name) like ''%'' || upper(:P40_LASTNAME) || ''%'' or upper(:P40_LASTNAME) is null))'
    ||'and ((upper(p.first_name) like ''%'' || upper(:P40_FIRSTNAME) || ''%'' or upper(:P40_FIRSTNAME) is null))'
    ||'and ((upper(f.format_ret) in (upper(l_vc_format)) or upper(:P40_FORMAT) is null))'
    ||'group by b.BOOK_ID, bk.book_id, bkk.book_id, b.TITLE, b.SUBTITLE, b.SERIES, b.VOLUME, b.ISBN, f.FORMAT_ret, b.DESCRIPTION, '
    ||'b.PUBLISHED, b.PURCHASED_FROM, b.COMMENTS, b.WEBSITE, c.LENGTH_MINS, pb.name, b.abridged, '
    ||'(nvl(d.disk01,0)+nvl(d.disk02,0)+nvl(d.disk03,0)+nvl(d.disk04,0)+nvl(d.disk05,0)+nvl(d.disk06,0)+nvl(d.disk07,0)+nvl(d.disk08,0)+'
    ||'nvl(d.disk09,0)+nvl(d.disk10,0)+nvl(d.disk11,0)+nvl(d.disk12,0)+nvl(d.disk13,0)+nvl(d.disk14,0)+nvl(d.disk15,0)+nvl(d.disk16,0)+nvl(d.disk17,0)+'
    ||'nvl(d.disk18,0)+nvl(d.disk19,0)+nvl(d.disk20,0)+nvl(d.disk21,0)+nvl(d.disk22,0)+nvl(d.disk23,0)+nvl(d.disk24,0)+nvl(d.disk25,0)+nvl(d.disk26,0)+'
    ||'nvl(d.disk27,0)+nvl(d.disk28,0)+nvl(d.disk29,0)+nvl(d.disk30,0)+nvl(d.disk31,0)+nvl(d.disk32,0)+nvl(d.disk33,0)+nvl(d.disk34,0)+nvl(d.disk35,0)+'
    ||'nvl(d.disk36,0)+nvl(d.disk37,0)+nvl(d.disk38,0)+nvl(d.disk39,0)+nvl(d.disk40,0)+nvl(d.disk41,0)+nvl(d.disk42,0)+nvl(d.disk43,0)+nvl(d.disk44,0)+'
    ||'nvl(d.disk45,0)+nvl(d.disk46,0)+nvl(d.disk47,0)+nvl(d.disk48,0)+nvl(d.disk49,0)+nvl(d.disk50,0))';
    RETURN q1;
    EXCEPTION
    WHEN OTHERS THEN
    RETURN q1;
    end create_report2;
    end;
    And here is what I have for my Region Source on my report:
    return lib2.report_query.create_report2(v('P40_FORMAT'));
    Here is my error when I run the page:
    failed to parse SQL query:
    ORA-00936: missing expression
    I have tried the region source line in many variations, this is just my latest one. None of them have worked. I am quite obviously missing something quite important and probably extremely silly. Any ideas?
    Thanks!
    Chrissy

    Chrissy,
    This is what the package returns as a query:
    select b.BOOK_ID, bk.book_id bkid, bkk.book_id bkkid,
    b.TITLE, b.SUBTITLE, b.SERIES, b.VOLUME, b.ISBN, f.FORMAT_RET,
    b.DESCRIPTION, .PUBLISHED,b.PURCHASED_FROM, b.COMMENTS, b.WEBSITE,
    c.LENGTH_MINS, stragg(p.last_name || ', ' || p.first_name) Author,
    stragg(p.person_id) person_id, pb.name PUBLISHER, decode(b.abridged,
    'Y','Abridged','N','Unabridged') Abridged,
    (nvl(d.disk01,0)+nvl(d.disk02,0)+nvl(d.disk03,0)+nvl(d.disk04,0)+nvl(d.disk05,0)
    nvl(d.disk06,0)nvl(d.disk07,0)+nvl(d.disk08,0)+nvl(d.disk09,0)+nvl(d.disk10,0)
    nvl(d.disk11,0)nvl(d.disk12,0)+nvl(d.disk13,0)+nvl(d.disk14,0)+nvl(d.disk15,0)
    nvl(d.disk16,0)nvl(d.disk17,0)+nvl(d.disk18,0)+nvl(d.disk19,0)+nvl(d.disk20,0)
    nvl(d.disk21,0)nvl(d.disk22,0)+nvl(d.disk23,0)+nvl(d.disk24,0)+nvl(d.disk25,0)
    nvl(d.disk26,0)nvl(d.disk27,0)+nvl(d.disk28,0)+nvl(d.disk29,0)+nvl(d.disk30,0)
    nvl(d.disk31,0)nvl(d.disk32,0)+nvl(d.disk33,0)+nvl(d.disk34,0)+nvl(d.disk35,0)
    nvl(d.disk36,0)nvl(d.disk37,0)+nvl(d.disk38,0)+nvl(d.disk39,0)+nvl(d.disk40,0)
    nvl(d.disk41,0)nvl(d.disk42,0)+nvl(d.disk43,0)+nvl(d.disk44,0)+nvl(d.disk45,0)
    nvl(d.disk46,0)nvl(d.disk47,0)+nvl(d.disk48,0)+nvl(d.disk49,0)+nvl(d.disk50,0)) total_tracksfrom book b,
    book bk,book bkk,person p,lkup_book_author la,lkup_book_publisher lp,
    lkup_book_format lkf,format f,publisher pb,conversion_info_audio c,
    lkup_book_disk_info dwhere b.book_id = la.book_idand b.book_id = bk.book_idand b.book_id = bkk.book_idand p.person_id = la.author_idand
    b.book_id = lp.book_idand b.book_id = c.book_idand b.book_id = d.book_idand
    b.book_id = lkf.book_idand lkf.format_id = f.format_idand pb.publisher_id(+) = lp.publisher_idand
    b.wishlist = 'N'and (upper(b.book_id) like '%' || upper(:P40_SEARCH) || '%'
    or upper(b.title) like '%' || upper(:P40_SEARCH) || '%'or upper(b.subtitle) like '%' ||
    upper(:P40_SEARCH) || '%'or upper(b.series) like '%' || upper(:P40_SEARCH) || '%'or
    upper(b.volume) like '%' || upper(:P40_SEARCH) || '%'or upper(b.isbn) like '%' ||
    upper(:P40_SEARCH) || '%'or upper(b.format) like '%' || upper(:P40_SEARCH) || '%'or upper(b.description) like '%' || upper(:P40_SEARCH) || '%'or upper(b.published)
    like '%' || upper(:P40_SEARCH) || '%'or upper(b.purchased_from) like '%' ||
    upper(:P40_SEARCH) || '%'or upper(b.comments) like '%' || upper(:P40_SEARCH)
    || '%'or upper(b.website) like '%' || upper(:P40_SEARCH) || '%'or
    upper(p.last_name) like '%' || upper(:P40_SEARCH) || '%'or upper(p.first_name)
    like '%' || upper(:P40_SEARCH) || '%'or upper(pb.name) like '%' ||
    upper(:P40_SEARCH) || '%'or upper(:P40_SEARCH) is null)and
    ((upper(b.title) like '%' || upper(:P40_TITLE) || '%' or
    upper(:P40_TITLE) is null))and ((upper(b.series) like '%' ||
    upper(:P40_SERIES) || '%' or upper(:P40_SERIES) is null))and
    ((upper(p.last_name) like '%' || upper(:P40_LASTNAME) || '%' or
    upper(:P40_LASTNAME) is null))and ((upper(p.first_name) like '%' ||
    upper(:P40_FIRSTNAME) || '%' or upper(:P40_FIRSTNAME) is null))and
    ((upper(f.format_ret) in (upper(l_vc_format)) or upper(:P40_FORMAT) is null))
    group by b.BOOK_ID, bk.book_id, bkk.book_id, b.TITLE, b.SUBTITLE, b.SERIES, b.VOLUME,
    b.ISBN, f.FORMAT_ret, b.DESCRIPTION, b.PUBLISHED, b.PURCHASED_FROM, b.COMMENTS, b.WEBSITE,
    c.LENGTH_MINS, pb.name, b.abridged, (nvl(d.disk01,0)+nvl(d.disk02,0)+nvl(d.disk03,0)
    nvl(d.disk04,0)nvl(d.disk05,0)+nvl(d.disk06,0)+nvl(d.disk07,0)+nvl(d.disk08,0)
    nvl(d.disk09,0)nvl(d.disk10,0)+nvl(d.disk11,0)+nvl(d.disk12,0)+nvl(d.disk13,0)
    nvl(d.disk14,0)nvl(d.disk15,0)+nvl(d.disk16,0)+nvl(d.disk17,0)+nvl(d.disk18,0)
    nvl(d.disk19,0)nvl(d.disk20,0)+nvl(d.disk21,0)+nvl(d.disk22,0)+nvl(d.disk23,0)
    nvl(d.disk24,0)nvl(d.disk25,0)+nvl(d.disk26,0)+nvl(d.disk27,0)+nvl(d.disk28,0)
    nvl(d.disk29,0)nvl(d.disk30,0)+nvl(d.disk31,0)+nvl(d.disk32,0)+nvl(d.disk33,0)
    nvl(d.disk34,0)nvl(d.disk35,0)+nvl(d.disk36,0)+nvl(d.disk37,0)+nvl(d.disk38,0)
    nvl(d.disk39,0)nvl(d.disk40,0)+nvl(d.disk41,0)+nvl(d.disk42,0)+nvl(d.disk43,0)
    nvl(d.disk44,0)nvl(d.disk45,0)+nvl(d.disk46,0)+nvl(d.disk47,0)+nvl(d.disk48,0)
    nvl(d.disk49,0)nvl(d.disk50,0))
    This query will never work. I marked only couple of errors you have there. Actually,
    I meant "formating" errors rather than "syntactical" errors. You are missing spaces
    all over the place. This is why I suggested to use a CLOB column in a test table
    to return the query for debugging purposes - this is how I do it at least, when I need
    to escape and concatenate a lot of code.
    If you are referencing item values from a user session in a function or a procedure,
    then you need to use the v('ITEM') syntax instead of :ITEM syntax. However, if the
    output of this procedure will be used as a function returning SQL query, you will
    be fine with :ITEM.
    Denes Kubicek
    http://deneskubicek.blogspot.com/
    http://htmldb.oracle.com/pls/otn/f?p=31517:1
    -------------------------------------------------------------------

  • How to use the result of a sql query for a max () function

    Hi
    I wrote a query on which i wrote
    "select max(id) from users "
    how can i use the returned value.
    if i made the var name ="userid"
    can it be userid.rows[0] or what.
    thnx for any help

    Hi!
    The result of this query will be the max ID of users' IDs.
    Let say we have:
    String sql="select max(users.id) from users";
    Statement st = ctx.conn.createStatement();
    ResultSet rs = st.executeQuery(sql);
    rs.next();     
    So you can get the max Id in the following way:     
    int maxId=rs.getInt("id");
    Regards,
    Rossi

  • Problem selecting MAX YEAR MAX MONTH MAX DATE in one query

    CREATE TABLE TEMP
    C_INVOICE_ID NUMBER(10),
    DIA NUMBER,
    MES NUMBER,
    ANO NUMBER,
    SOCIO_NEGOCIO NVARCHAR2(60) NOT NULL,
    PRODUCTO_NOM NVARCHAR2(60) NOT NULL,
    M_PRODUCT_ID NUMBER(10),
    CATEGORIA NVARCHAR2(60) NOT NULL,
    COSTO NUMBER
    INSERT INTO TEMP VALUES(10111,1,2,2010,'1585','ALURON 100MG X 30 TABLETAS',1530,15,1.15);
    INSERT INTO TEMP VALUES(1015,15,2,2010,'1520','ALURON 100MG X 30 TABLETAS',1530,15,2.15);
    INSERT INTO TEMP VALUES(5654,5,2,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.2);
    INSERT INTO TEMP VALUES(15321,4,6,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
    INSERT INTO TEMP VALUES(13548,8,6,2010,'1585','AMARYL 2MG X 15 TABLETAS',1531,15,4.3);
    INSERT INTO TEMP VALUES(19456,31,4,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4);
    INSERT INTO TEMP VALUES(116544,8,8,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
    INSERT INTO TEMP VALUES(132,2,3,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.1);
    INSERT INTO TEMP VALUES(168,15,1,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.9);
    INSERT INTO TEMP VALUES(4898,7,4,2010,'1220','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
    INSERT INTO TEMP VALUES(15132,25,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.4);
    INSERT INTO TEMP VALUES(1684,18,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.3);
    INSERT INTO TEMP VALUES(14988,8,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,2.9);
    INSERT INTO TEMP VALUES(84941,8,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.1);
    INSERT INTO TEMP VALUES(1155,7,4,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.7);
    INSERT INTO TEMP VALUES(184,1,1,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
    INSERT INTO TEMP VALUES(48994,8,4,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.7);
    INSERT INTO TEMP VALUES(1465465,9,5,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
    INSERT INTO TEMP VALUES(16,18,6,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
    INSERT INTO TEMP VALUES(894886,20,4,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
    CREATE TABLE TEMP
    C_INVOICE_ID NUMBER(10),
    DIA NUMBER,
    MES NUMBER,
    ANO NUMBER,
    SOCIO_NEGOCIO NVARCHAR2(60) NOT NULL,
    PRODUCTO_NOM NVARCHAR2(60) NOT NULL,
    M_PRODUCT_ID NUMBER(10),
    CATEGORIA NVARCHAR2(60) NOT NULL,
    COSTO NUMBER
    INSERT INTO TEMP VALUES(10111,1,2,2010,'1585','ALURON 100MG X 30 TABLETAS',1530,15,1.15);
    INSERT INTO TEMP VALUES(1015,15,2,2010,'1520','ALURON 100MG X 30 TABLETAS',1530,15,2.15);
    INSERT INTO TEMP VALUES(5654,5,2,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.2);
    INSERT INTO TEMP VALUES(15321,4,6,2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
    INSERT INTO TEMP VALUES(13548,8,6,2010,'1585','AMARYL 2MG X 15 TABLETAS',1531,15,4.3);
    INSERT INTO TEMP VALUES(19456,31,4,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4);
    INSERT INTO TEMP VALUES(116544,8,8,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);
    INSERT INTO TEMP VALUES(132,2,3,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.1);
    INSERT INTO TEMP VALUES(168,15,1,2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.9);
    INSERT INTO TEMP VALUES(4898,7,4,2010,'1220','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
    INSERT INTO TEMP VALUES(15132,25,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.4);
    INSERT INTO TEMP VALUES(1684,18,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.3);
    INSERT INTO TEMP VALUES(14988,8,8,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,2.9);
    INSERT INTO TEMP VALUES(84941,8,9,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.1);
    INSERT INTO TEMP VALUES(1155,7,4,2010,'1585','AMOXAL 250MG X 75ML SUSPENSION',1534,15,4.7);
    INSERT INTO TEMP VALUES(184,1,1,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
    INSERT INTO TEMP VALUES(48994,8,4,2010,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.7);
    INSERT INTO TEMP VALUES(1465465,9,5,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.8);
    INSERT INTO TEMP VALUES(16,18,6,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
    INSERT INTO TEMP VALUES(894886,20,4,2009,'1520','AMOXAL 250MG X 75ML SUSPENSION',1534,15,3.9);
    I have this query so far,
    SELECT
    MAX (TEMP.COSTO) COSTO,
    TEMP.M_PRODUCT_ID,
    TEMP.ANO
    FROM TEMP TEMP
    INNER JOIN(
    SELECT MAX(ANO) ANO, M_PRODUCT_ID
    FROM TEMP I
    GROUP BY M_PRODUCT_ID
    ) LA ON LA.ANO = TEMP.ANO AND LA.M_PRODUCT_ID = TEMP.M_PRODUCT_ID
    GROUP BY
    TEMP.M_PRODUCT_ID,
    TEMP.ANO
    but my intention is not to have the max cost, my intention is to query in this order
    first i need to select distinct m_product_id then
    for every m_product_id i need to
    filter max (ano) then filter max (mes) then filter max (dia)
    I need the result set like this.
    C_INVOICE_ID DIA MES ANO SOCIO PRODUCTO_NOM M_PRODUCT_ID CATERGORIA COSTO
    1015 15 2 2010 1520 ALURON 100MG X 30 TABLETAS 1530 15 2.15
    5654 5 2 2010 1520 AMARYL 2MG X 15 TABLETAS 1531 15 4.2
    15132 25 9 2010 1585 AMOXAL 250MG X 75ML SUSPENSION 1534 15 3.4
    please i really apritiated any help, thanks pd:i'm using oracle 9i

    Hi,
    Thanks for posting the CREATE TABLE and INSERT statements. Why are there two tables, and two sets of data? Was that a mistake?
    Sorry, I don't uderstand the problem.
    For m_product_id=1531, for example, why do you want
    INSERT INTO TEMP VALUES(5654,     5, 2, 2010,'1520','AMARYL 2MG X 15 TABLETAS',1531,15,4.2);selected, and not
    INSERT INTO TEMP VALUES(116544,     8, 8, 2010,'1220','AMARYL 2MG X 15 TABLETAS',1531,15,4.8);Both rows have ano=2010, so don't you want the one with the higher mes (8 > 2)?
    I think what you'll want is a Top-N Query , something like this:
    WITH     got_r_num     AS
         SELECT     temp.*     -- or list columns you want
         ,     RANK () OVER ( PARTITION BY  m_product_id
                          ORDER BY          ano     DESC     NULLS FIRST
                          ,          mes     DESC     NULLS FIRST
                          ,          dia     DESC     NULLS FIRST
                        )          AS r_num
         FROM     temp
    --     WHERE     ...     -- any filtering goes here
    SELECT     *     -- or list all columns except r_num
    FROM     got_r_num
    WHERE     r_num     = 1
    ;What if there's a tie? For example, if you add another row to the sample data:
    INSERT INTO TEMP VALUES(9876,     15,2, 2010,'1520','ALURON 100MG X 30 TABLETAS',1530,15,2.15);The query above would include both c_invoice_id=9876 and 1015. If you want just one of those rows, add more expressions to the analytic ORDER BY clause and/or use ROW_NUMBER instead of RANK.

  • A challenging dynamic SQL query problem

    hi All,
    I have a very interesting problem at work:
    We have this particular table defined as follows :
    CREATE TABLE sales_data (
    sales_id NUMBER,
    sales_m01 NUMBER,
    sales_m02 NUMBER,
    sales_m03 NUMBER,
    sales_m04 NUMBER,
    sales_m05 NUMBER,
    sales_m06 NUMBER,
    sales_m07 NUMBER,
    sales_m08 NUMBER,
    sales_m09 NUMBER,
    sales_m10 NUMBER,
    sales_m11 NUMBER,
    sales_m12 NUMBER,
    sales_prior_yr NUMBER );
    The columns 'sales_m01 ..... sales_m12' represents aggregated monthly sales, in which 'sales_m01' translates to 'sales for the month of january, january being the first month, 'sales_m02' sales for the month of february, and so on.
    The problem I face is that we have a project which requires that a parameter be passed to a stored procedure which stands for the month number which is then used to build a SQL query with the following required field aggregations, which depends on the parameter passed :
    Sample 1 : parameter input: 4
    Dynamically-built SQL query should be :
    SELECT
    SUM(sales_m04) as CURRENT_SALES,
    SUM(sales_m01+sales_m02+sales_m03+sales_m04) SALES_YTD
    FROM
    sales_data
    WHERE
    sales_id = '0599768';
    Sample 2 : parameter input: 8
    Dynamically-built SQL query should be :
    SELECT
    SUM(sales_m08) as CURRENT_SALES,
    SUM(sales_m01+sales_m02+sales_m03+sales_m04+
    sales_m05+sales_m06+sales_m07+sales_m08) SALES_YTD
    FROM
    sales_data
    WHERE
    sales_id = '0599768';
    So in a sense, the contents of SUM(sales_m01 ....n) would vary depending on the parameter passed, which should be a number between 1 .. 12 which corresponds to a month, which in turn corresponds to an actual field range on the table itself. The resulting dynamic query should only aggregate those columns/fields in the table which falls within the range given by the input parameter and disregards all the remaining columns/fields.
    Any solution is greatly appreciated.
    Thanks.

    Hi another simpler approach is using decode
    try like this
    SQL> CREATE TABLE sales_data (
      2  sales_id NUMBER,
      3  sales_m01 NUMBER,
      4  sales_m02 NUMBER,
      5  sales_m03 NUMBER,
      6  sales_m04 NUMBER,
      7  sales_m05 NUMBER,
      8  sales_m06 NUMBER,
      9  sales_m07 NUMBER,
    10  sales_m08 NUMBER,
    11  sales_m09 NUMBER,
    12  sales_m10 NUMBER,
    13  sales_m11 NUMBER,
    14  sales_m12 NUMBER,
    15  sales_prior_yr NUMBER );
    Table created.
    SQL> select * from sales_data;
      SALES_ID  SALES_M01  SALES_M02  SALES_M03  SALES_M04  SALES_M05  SALES_M06  SALES_M07  SALES_M08  SALES_M09  SALES_M10  SALES_M11  SALES_M12 SALES_PRIOR_YR
             1        124        123        145        146        124        126        178        189        456        235        234        789          19878
             2        124        123        145        146        124        126        178        189        456        235        234        789          19878
             1        100        200        300        400        500        150        250        350        450        550        600        700          10000
             1        101        201        301        401        501        151        251        351        451        551        601        701          10000----now for your requirement. see below query if there is some problem then tell.
    SQL> SELECT sum(sales_m&input_data), DECODE (&input_data,
      2                 1, SUM (sales_m01),
      3                 2, SUM (sales_m01 + sales_m02),
      4                 3, SUM (sales_m01 + sales_m02 + sales_m03),
      5                 4, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04),
      6                 5, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04 + sales_m05),
      7                 6, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06),
      8                 7, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07),
      9                 8, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07+sales_m08),
    10                 9, SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07+sales_m08+sales_m09),
    11                 10,SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07+sales_m08+sales_m09+sales_m10),
    12                 11,SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07+sales_m08+sales_m09+sales_m10+sales_m11),
    13                 12,SUM (sales_m01 + sales_m02 + sales_m03 + sales_m04+sales_m05+sales_m06+sales_m07+sales_m08+sales_m09+sales_m10+sales_m11+sales_m12)
    14                ) total
    15    FROM sales_data
    16   WHERE sales_id = 1;
    Enter value for input_data: 08
    Enter value for input_data: 08
    old   1: SELECT sum(sales_m&input_data), DECODE (&input_data,
    new   1: SELECT sum(sales_m08), DECODE (08,
    SUM(SALES_M08)      TOTAL
               890       5663

  • Sql query for running sum(using aggregate)

    <pre>
    Table name table1 (no, amount)
    insert into table1 values(1, 10) ;
    insert into table1 values(2 ,-10) ;
    insert into table1 values(3, -20) ;
    insert into table1 values(4,  -30) ;
    insert into table1 values(5,40) ;
    and i am expecting the result in this manner
    no
    sum (amount)
    1
    10
    2
    0
    3
    -20
    4
    -50
    5
    -10
    select no,sum(amount) over(order by no) from table1;
    but with this query i am getting the result in below manner
    no
    sum (amount)
    1
    10
    2
    20
    3
    40
    4
    70
    5
    110
    which is not excepted result, could some one help me in getting excepted results ,could any one provide the proper query for this
    </pre>

    h
    Hi Friends,
    sorry to trouble you,i did  not have oracle instance installed on my machine to check the query ,
    this is some test query which is some resemblance with actual query in my project
    actually the requirement is like this ,this is the master table 
      NO                            amount
             1                         10
             2                         100
             3                         120
             4                         50
             5                         41
    using some decoding function in the query the result came like this
    NO                        decode(amount,......) quantity
             1                          10
             2                         -10
             3                         -20
             4                         -30
             5                          41
    on this decode function i am trying to using aggregate function SUM,but in that case in stood of giving
    ABS value , it is giving   in proper value like below result
      NO        decode(amount,......) quantity    aggregate sum
             1                          10                10
             2                         -10                20
             3                         -20                40
             4                         -30                70
             5                          41                111
    but i excepted the result  ABS  value like below
       NO           decode(amount,......) quantity    aggregate sum
             1                         10                 10
             2                         -10                0
             3                         -20               -20
             4                         -30               -50
             5                          41                -9
       my question is aggregate function on this decoded values have any impact on the result?
       for this question your are unable to help me ,tomorrow i will get exact table structure and exact query which i am using
       in my project

  • Sql query slow due to case statement on Joins

    Hi
    The sql query runs very slow for 30 min when the below case statement is added on the joins. Could you please let me know how to tune it. if the case statement is not there then it runs only for 1 min.
    *( CASE*
    WHEN PO_DIST_GL_CODE_COMB.SEGMENT2 <> '1000'
    THEN  PO_DIST_GL_CODE_COMB.SEGMENT1 || PO_DIST_GL_CODE_COMB.SEGMENT2 || '_' || NVL(PO_DIST_GL_CODE_COMB.SEGMENT6,'000')
    WHEN DT_REQ_ALL.EMPMGMTCD IS NOT NULL AND
    PO_DIST_GL_CODE_COMB.SEGMENT2 = '1000'
    THEN DT_REQ_ALL.EMPMGMTCD
    END =DB2.DB2_FDW_MGMT_V.MH_CHILD  )
    SELECT  DISTINCT
      D.DB2_FDW_MGMT_V.RC_PARENT,
      DT_REQ_ALL.FULL_NAME,
      DT_REQ_ALL.EMP_COMPANY_CODE,
      DT_REQ_ALL.EMP_COST_CENTER,
      PO.PO_VENDORS.VENDOR_NAME,
      PO_PO_HEADERS_ALL2.SEGMENT1,
      PO_PO_HEADERS_ALL2.CREATION_DATE,
      PO_DIST_GL_CODE_COMB.SEGMENT1,
      PO_DIST_GL_CODE_COMB.SEGMENT2,
      PO_PO_HEADERS_ALL2.CURRENCY_CODE,
      PO_INV_DIST_ALL.INVOICE_NUM,
      PO_INV_DIST_ALL.INVOICE_DATE,
      (PO_INV_DIST_ALL.INVOICE_AMOUNT* PO_Rates_GL_DR.CONVERSION_RATE),
      (NVL(to_number(PO_DIST_ALL.AMOUNT_BILLED),0) * PO_Rates_GL_DR.CONVERSION_RATE),
      PO_LINES_LOC.LINE_NUM,
      GL.GL_SETS_OF_BOOKS.NAME,
      CASE
            WHEN TRUNC(PO_PO_HEADERS_ALL2.CREATION_DATE) > PO_INV_DIST_ALL.INVOICE_DATE
            THEN 1
            ELSE 0
        END ,
      PO.PO_REQUISITION_LINES_ALL.LINE_LOCATION_ID,
      TRUNC(PO_PO_HEADERS_ALL2.CREATION_DATE,'WW') + 8 WEEK_Ending
    FROM
      DB2.DB2_FDW_MGMT_V,
       PO.PO_VENDORS,
      PO.PO_HEADERS_ALL  PO_PO_HEADERS_ALL2,
      GL.GL_CODE_COMBINATIONS  PO_DIST_GL_CODE_COMB,
      AP.AP_INVOICES_ALL  PO_INV_DIST_ALL,
       PO.PO_DISTRIBUTIONS_ALL  PO_DIST_ALL,
      PO.PO_LINES_ALL  PO_LINES_LOC,
      GL.GL_SETS_OF_BOOKS,
      PO.PO_REQUISITION_LINES_ALL,
      PO.PO_LINE_LOCATIONS_ALL,
      AP.AP_INVOICE_DISTRIBUTIONS_ALL  PO_DIST_INV_DIST_ALL,
      APPS.HR_OPERATING_UNITS,
      PO.PO_REQ_DISTRIBUTIONS_ALL,
       SELECT DISTINCT
                            PO_RDA.DISTRIBUTION_ID,
                            PO_RLA.requisition_line_id,
                            PO_RHA.DESCRIPTION PO_Descr,
                            PO_RHA.NOTE_TO_AUTHORIZER PO_Justification,
                            Req_Emp.FULL_NAME,
                            GL_CC.SEGMENT1         Req_Company_Code,
                            GL_CC.SEGMENT2         Req_Cost_Center,
                            Req_Emp_CC.SEGMENT1    Emp_Company_Code,
                            Req_Emp_CC.SEGMENT2    Emp_Cost_Center,
                            (Case
                            When GL_CC.SEGMENT2 <> 8000
                            Then TRUNC(GL_CC.SEGMENT1) || TRUNC(GL_CC.SEGMENT2) || '_' || NVL(GL_CC.SEGMENT6,'000')
                            Else TRUNC(Req_Emp_CC.SEGMENT1) || TRUNC(Req_Emp_CC.SEGMENT2) || '_' || NVL(Req_Emp_CC.SEGMENT6,'000')
                            End) EmpMgmtCD
                FROM
                            PO.po_requisition_lines_all PO_rla,
                            PO.po_requisition_headers_all PO_rha,
                            PO.PO_REQ_DISTRIBUTIONS_ALL po_RDA,
                            GL.GL_CODE_COMBINATIONS gl_cc,
                            HR.PER_ALL_PEOPLE_F  Req_Emp,
                            HR.PER_ALL_ASSIGNMENTS_F Req_Emp_Assign,
                            HR.hr_all_organization_units Req_Emp_Org,
                            HR.pay_cost_allocation_keyflex Req_Emp_CC
                WHERE
                            PO_RDA.CODE_COMBINATION_ID = GL_CC.CODE_COMBINATION_ID and
                            PO_RLA.REQUISITION_LINE_ID = PO_RDA.REQUISITION_LINE_ID AND
                            PO_RLA.to_person_id = Req_Emp.PERSON_ID AND
                            PO_RLA.REQUISITION_HEADER_ID = PO_RHA.REQUISITION_HEADER_ID AND
                            (trunc(PO_rla.CREATION_DATE) between Req_Emp.effective_start_date and Req_Emp.effective_end_date OR
                            Req_Emp.effective_start_date IS NULL) AND
                            Req_Emp.PERSON_ID = Req_Emp_Assign.PERSON_ID AND
                            Req_Emp_Assign.organization_id = Req_Emp_Org.organization_id AND
                            (trunc(PO_rla.CREATION_DATE) between Req_Emp_Assign.effective_start_date and Req_Emp_Assign.effective_end_date OR
            Req_Emp_Assign.effective_start_date IS NULL) AND
            Req_Emp_Assign.primary_flag = 'Y' AND
            Req_Emp_Assign.assignment_type = 'E' AND
            Req_Emp_Org.cost_allocation_keyflex_id = Req_Emp_CC.cost_allocation_keyflex_id
      )  DT_REQ_ALL,
      SELECT
            FROM_CURRENCY,
            TO_CURRENCY,
            CONVERSION_DATE,
            CONVERSION_RATE
        FROM GL.GL_DAILY_RATES
        UNION
        SELECT Distinct
            'USD',
            'USD',
            CONVERSION_DATE,
            1
        FROM GL.GL_DAILY_RATES
      )  PO_Rates_GL_DR
    WHERE
      ( PO_DIST_GL_CODE_COMB.CODE_COMBINATION_ID=PO_DIST_ALL.CODE_COMBINATION_ID  )
      AND  ( PO_DIST_ALL.LINE_LOCATION_ID=PO.PO_LINE_LOCATIONS_ALL.LINE_LOCATION_ID  )
      AND  ( PO_PO_HEADERS_ALL2.VENDOR_ID=PO.PO_VENDORS.VENDOR_ID  )
      AND  ( PO_PO_HEADERS_ALL2.ORG_ID=APPS.HR_OPERATING_UNITS.ORGANIZATION_ID  )
      AND  ( GL.GL_SETS_OF_BOOKS.SET_OF_BOOKS_ID=APPS.HR_OPERATING_UNITS.SET_OF_BOOKS_ID  )
      AND  ( PO_PO_HEADERS_ALL2.CURRENCY_CODE=PO_Rates_GL_DR.FROM_CURRENCY  )
      AND  ( trunc(PO_PO_HEADERS_ALL2.CREATION_DATE)=PO_Rates_GL_DR.CONVERSION_DATE  )
      AND  ( PO_DIST_ALL.REQ_DISTRIBUTION_ID=PO.PO_REQ_DISTRIBUTIONS_ALL.DISTRIBUTION_ID(+)  )
      AND  ( PO.PO_REQ_DISTRIBUTIONS_ALL.REQUISITION_LINE_ID=PO.PO_REQUISITION_LINES_ALL.REQUISITION_LINE_ID(+)  )
      AND  ( PO_LINES_LOC.PO_HEADER_ID=PO_PO_HEADERS_ALL2.PO_HEADER_ID  )
      AND  ( PO.PO_LINE_LOCATIONS_ALL.PO_LINE_ID=PO_LINES_LOC.PO_LINE_ID  )
      AND  ( PO_DIST_ALL.REQ_DISTRIBUTION_ID=DT_REQ_ALL.DISTRIBUTION_ID(+)  )
      AND  ( PO_DIST_ALL.PO_DISTRIBUTION_ID=PO_DIST_INV_DIST_ALL.PO_DISTRIBUTION_ID(+)  )
      AND  ( PO_INV_DIST_ALL.INVOICE_ID(+)=PO_DIST_INV_DIST_ALL.INVOICE_ID  )
      AND  ( PO_INV_DIST_ALL.SOURCE(+) <> 'XML GATEWAY'   )
      AND 
       ( NVL(PO_PO_HEADERS_ALL2.CANCEL_FLAG,'N') <> 'Y'   )
       AND
       ( NVL(PO_PO_HEADERS_ALL2.CLOSED_CODE, 'OPEN') <> 'FINALLY CLOSED'  )
       AND
       ( NVL(PO_PO_HEADERS_ALL2.AUTHORIZATION_STATUS,'IN PROCESS') <> 'REJECTED'  )
       AND
       ( TRUNC(PO_PO_HEADERS_ALL2.CREATION_DATE)  BETWEEN TO_DATE('01-jan-2011') AND TO_DATE('04-jan-2011')  )
       AND
       PO_Rates_GL_DR.TO_CURRENCY  =  'USD'
         AND
       DB2.DB2_FDW_MGMT_V.RC_PARENT  In  ( 'Unavailable','Corp','Commercial'  )
       AND
      ( CASE
            WHEN PO_DIST_GL_CODE_COMB.SEGMENT2 <> '1000'
            THEN  PO_DIST_GL_CODE_COMB.SEGMENT1 || PO_DIST_GL_CODE_COMB.SEGMENT2 || '_' || NVL(PO_DIST_GL_CODE_COMB.SEGMENT6,'000')
            WHEN DT_REQ_ALL.EMPMGMTCD IS NOT NULL AND
                    PO_DIST_GL_CODE_COMB.SEGMENT2 = '1000'
            THEN DT_REQ_ALL.EMPMGMTCD     
        END =DB2.DB2_FDW_MGMT_V.MH_CHILD  )Explain plan. sorry can't get the explain plan from sql. this is from toad.
    Plan
    SELECT STATEMENT  ALL_ROWSCost: 53,932  Bytes: 2,607  Cardinality: 1                                                                                                                               
         79 HASH UNIQUE  Cost: 53,932  Bytes: 2,607  Cardinality: 1                                                                                                                          
              78 NESTED LOOPS OUTER  Cost: 53,931  Bytes: 2,607  Cardinality: 1                                                                                                                     
                   75 NESTED LOOPS OUTER  Cost: 53,928  Bytes: 2,560  Cardinality: 1                                                                                                                
                        72 NESTED LOOPS  Cost: 53,902  Bytes: 2,552  Cardinality: 1                                                                                                           
                             69 NESTED LOOPS OUTER  Cost: 53,900  Bytes: 2,533  Cardinality: 1                                                                                                      
                                  66 NESTED LOOPS OUTER  Cost: 53,898  Bytes: 2,521  Cardinality: 1                                                                                                 
                                       63 HASH JOIN OUTER  Cost: 53,896  Bytes: 2,509  Cardinality: 1                                                                                            
                                            40 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_DISTRIBUTIONS_ALL Cost: 3  Bytes: 26  Cardinality: 1                                                                                       
                                                 39 NESTED LOOPS  Cost: 17,076  Bytes: 2,400  Cardinality: 1                                                                                  
                                                      37 NESTED LOOPS  Cost: 17,073  Bytes: 2,374  Cardinality: 1                                                                             
                                                           34 NESTED LOOPS  Cost: 17,070  Bytes: 2,362  Cardinality: 1                                                                        
                                                                31 NESTED LOOPS  Cost: 17,066  Bytes: 2,347  Cardinality: 1                                                                   
                                                                     29 NESTED LOOPS  Cost: 17,066  Bytes: 2,339  Cardinality: 1                                                              
                                                                          26 NESTED LOOPS  Cost: 17,065  Bytes: 2,312  Cardinality: 1                                                         
                                                                               23 NESTED LOOPS  Cost: 17,064  Bytes: 2,287  Cardinality: 1                                                    
                                                                                    20 NESTED LOOPS  Cost: 17,062  Bytes: 2,261  Cardinality: 1                                               
                                                                                         17 NESTED LOOPS  Cost: 17,056  Bytes: 6,678  Cardinality: 3                                          
                                                                                              15 HASH JOIN  Cost: 17,056  Bytes: 6,663  Cardinality: 3                                     
                                                                                                   13 MERGE JOIN CARTESIAN  Cost: 135  Bytes: 30,352  Cardinality: 14                                
                                                                                                        5 VIEW VIEW DB2.DB2_FDW_MGMT_V Cost: 4  Bytes: 2,128  Cardinality: 1                           
                                                                                                             4 SORT UNIQUE  Cost: 4  Cardinality: 1                      
                                                                                                                  3 UNION-ALL                 
                                                                                                                       1 REMOTE REMOTE SERIAL_FROM_REMOTE PRDFDW.WORLD          
                                                                                                                       2 FAST DUAL  Cost: 3  Cardinality: 1            
                                                                                                        12 BUFFER SORT  Cost: 135  Bytes: 560  Cardinality: 14                           
                                                                                                             11 VIEW DB2. Cost: 131  Bytes: 560  Cardinality: 14                      
                                                                                                                  10 SORT UNIQUE  Cost: 131  Bytes: 310  Cardinality: 14                 
                                                                                                                       9 UNION-ALL            
                                                                                                                            7 TABLE ACCESS BY INDEX ROWID TABLE GL.GL_DAILY_RATES Cost: 65  Bytes: 270  Cardinality: 9       
                                                                                                                                 6 INDEX SKIP SCAN INDEX (UNIQUE) GL.GL_DAILY_RATES_U1 Cost: 64  Cardinality: 1 
                                                                                                                            8 INDEX SKIP SCAN INDEX (UNIQUE) GL.GL_DAILY_RATES_U1 Cost: 64  Bytes: 4,368  Cardinality: 546       
                                                                                                   14 TABLE ACCESS FULL TABLE PO.PO_HEADERS_ALL Cost: 16,920  Bytes: 32,754  Cardinality: 618                                
                                                                                              16 INDEX UNIQUE SCAN INDEX (UNIQUE) HR.HR_ORGANIZATION_UNITS_PK Cost: 0  Bytes: 5  Cardinality: 1                                     
                                                                                         19 TABLE ACCESS BY INDEX ROWID TABLE HR.HR_ORGANIZATION_INFORMATION Cost: 2  Bytes: 35  Cardinality: 1                                          
                                                                                              18 INDEX RANGE SCAN INDEX HR.HR_ORGANIZATION_INFORMATIO_FK2 Cost: 1  Cardinality: 2                                     
                                                                                    22 TABLE ACCESS BY INDEX ROWID TABLE HR.HR_ORGANIZATION_INFORMATION Cost: 2  Bytes: 26  Cardinality: 1                                               
                                                                                         21 INDEX RANGE SCAN INDEX HR.HR_ORGANIZATION_INFORMATIO_FK2 Cost: 1  Cardinality: 1                                          
                                                                               25 TABLE ACCESS BY INDEX ROWID TABLE GL.GL_SETS_OF_BOOKS Cost: 1  Bytes: 25  Cardinality: 1                                                    
                                                                                    24 INDEX UNIQUE SCAN INDEX (UNIQUE) GL.GL_SETS_OF_BOOKS_U2 Cost: 0  Cardinality: 1                                               
                                                                          28 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_VENDORS Cost: 1  Bytes: 27  Cardinality: 1                                                         
                                                                               27 INDEX UNIQUE SCAN INDEX (UNIQUE) PO.PO_VENDORS_U1 Cost: 0  Cardinality: 1                                                    
                                                                     30 INDEX UNIQUE SCAN INDEX (UNIQUE) HR.HR_ALL_ORGANIZATION_UNTS_TL_PK Cost: 0  Bytes: 8  Cardinality: 1                                                              
                                                                33 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_LINES_ALL Cost: 4  Bytes: 60  Cardinality: 4                                                                   
                                                                     32 INDEX RANGE SCAN INDEX (UNIQUE) PO.PO_LINES_U2 Cost: 2  Cardinality: 4                                                              
                                                           36 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_LINE_LOCATIONS_ALL Cost: 3  Bytes: 12  Cardinality: 1                                                                        
                                                                35 INDEX RANGE SCAN INDEX PO.PO_LINE_LOCATIONS_N1 Cost: 2  Cardinality: 1                                                                   
                                                      38 INDEX RANGE SCAN INDEX PO.PO_DISTRIBUTIONS_N1 Cost: 2  Cardinality: 1                                                                             
                                            62 VIEW DB2. Cost: 36,819  Bytes: 1,090  Cardinality: 10                                                                                       
                                                 61 HASH UNIQUE  Cost: 36,819  Bytes: 2,580  Cardinality: 10                                                                                  
                                                      60 NESTED LOOPS  Cost: 36,818  Bytes: 2,580  Cardinality: 10                                                                             
                                                           57 NESTED LOOPS  Cost: 36,798  Bytes: 2,390  Cardinality: 10                                                                        
                                                                54 NESTED LOOPS  Cost: 36,768  Bytes: 2,220  Cardinality: 10                                                                   
                                                                     51 NESTED LOOPS  Cost: 36,758  Bytes: 1,510  Cardinality: 10                                                              
                                                                          48 NESTED LOOPS  Cost: 36,747  Bytes: 1,050  Cardinality: 10                                                         
                                                                               45 HASH JOIN  Cost: 36,737  Bytes: 960  Cardinality: 10                                                    
                                                                                    43 HASH JOIN  Cost: 34,602  Bytes: 230,340  Cardinality: 3,490                                               
                                                                                         41 TABLE ACCESS FULL TABLE HR.PER_ALL_PEOPLE_F Cost: 1,284  Bytes: 1,848,420  Cardinality: 44,010                                          
                                                                                         42 TABLE ACCESS FULL TABLE PO.PO_REQUISITION_LINES_ALL Cost: 31,802  Bytes: 18,340,080  Cardinality: 764,170                                          
                                                                                    44 TABLE ACCESS FULL TABLE HR.PER_ALL_ASSIGNMENTS_F Cost: 2,134  Bytes: 822,540  Cardinality: 27,418                                               
                                                                               47 TABLE ACCESS BY INDEX ROWID TABLE HR.HR_ALL_ORGANIZATION_UNITS Cost: 1  Bytes: 9  Cardinality: 1                                                    
                                                                                    46 INDEX UNIQUE SCAN INDEX (UNIQUE) HR.HR_ORGANIZATION_UNITS_PK Cost: 0  Cardinality: 1                                               
                                                                          50 TABLE ACCESS BY INDEX ROWID TABLE HR.PAY_COST_ALLOCATION_KEYFLEX Cost: 1  Bytes: 46  Cardinality: 1                                                         
                                                                               49 INDEX UNIQUE SCAN INDEX (UNIQUE) HR.PAY_COST_ALLOCATION_KEYFLE_PK Cost: 0  Cardinality: 1                                                    
                                                                     53 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_REQUISITION_HEADERS_ALL Cost: 1  Bytes: 71  Cardinality: 1                                                              
                                                                          52 INDEX UNIQUE SCAN INDEX (UNIQUE) PO.PO_REQUISITION_HEADERS_U1 Cost: 0  Cardinality: 1                                                         
                                                                56 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_REQ_DISTRIBUTIONS_ALL Cost: 3  Bytes: 17  Cardinality: 1                                                                   
                                                                     55 INDEX RANGE SCAN INDEX PO.PO_REQ_DISTRIBUTIONS_N1 Cost: 2  Cardinality: 1                                                              
                                                           59 TABLE ACCESS BY INDEX ROWID TABLE GL.GL_CODE_COMBINATIONS Cost: 2  Bytes: 19  Cardinality: 1                                                                        
                                                                58 INDEX UNIQUE SCAN INDEX (UNIQUE) GL.GL_CODE_COMBINATIONS_U1 Cost: 1  Cardinality: 1                                                                   
                                       65 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_REQ_DISTRIBUTIONS_ALL Cost: 2  Bytes: 12  Cardinality: 1                                                                                            
                                            64 INDEX UNIQUE SCAN INDEX (UNIQUE) PO.PO_REQ_DISTRIBUTIONS_U1 Cost: 1  Cardinality: 1                                                                                       
                                  68 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_REQUISITION_LINES_ALL Cost: 2  Bytes: 12  Cardinality: 1                                                                                                 
                                       67 INDEX UNIQUE SCAN INDEX (UNIQUE) PO.PO_REQUISITION_LINES_U1 Cost: 1  Cardinality: 1                                                                                            
                             71 TABLE ACCESS BY INDEX ROWID TABLE GL.GL_CODE_COMBINATIONS Cost: 2  Bytes: 19  Cardinality: 1                                                                                                      
                                  70 INDEX UNIQUE SCAN INDEX (UNIQUE) GL.GL_CODE_COMBINATIONS_U1 Cost: 1  Cardinality: 1                                                                                                 
                        74 TABLE ACCESS BY INDEX ROWID TABLE AP.AP_INVOICE_DISTRIBUTIONS_ALL Cost: 26  Bytes: 16  Cardinality: 2                                                                                                           
                             73 INDEX RANGE SCAN INDEX AP.AP_INVOICE_DISTRIBUTIONS_N7 Cost: 2  Cardinality: 37                                                                                                      
                   77 TABLE ACCESS BY INDEX ROWID TABLE AP.AP_INVOICES_ALL Cost: 3  Bytes: 47  Cardinality: 1                                                                                                                
                        76 INDEX RANGE SCAN INDEX (UNIQUE) AP.AP_INVOICES_U1 Cost: 2  Cardinality: 1                                                                                                           Thanks

    Forming a new table "new_table" with 3 tables which particiapate in CASE statement logic.
    with  DT_REQ_ALL  as
       SELECT DISTINCT
                            PO_RDA.DISTRIBUTION_ID,
                            PO_RLA.requisition_line_id,
                            PO_RHA.DESCRIPTION PO_Descr,
                            PO_RHA.NOTE_TO_AUTHORIZER PO_Justification,
                            Req_Emp.FULL_NAME,
                            GL_CC.SEGMENT1         Req_Company_Code,
                            GL_CC.SEGMENT2         Req_Cost_Center,
                            Req_Emp_CC.SEGMENT1    Emp_Company_Code,
                            Req_Emp_CC.SEGMENT2    Emp_Cost_Center,
                            (Case
                            When GL_CC.SEGMENT2  8000
                            Then TRUNC(GL_CC.SEGMENT1) || TRUNC(GL_CC.SEGMENT2) || '_' || NVL(GL_CC.SEGMENT6,'000')
                            Else TRUNC(Req_Emp_CC.SEGMENT1) || TRUNC(Req_Emp_CC.SEGMENT2) || '_' || NVL(Req_Emp_CC.SEGMENT6,'000')
                            End) EmpMgmtCD
                FROM
                            PO.po_requisition_lines_all PO_rla,
                            PO.po_requisition_headers_all PO_rha,
                            PO.PO_REQ_DISTRIBUTIONS_ALL po_RDA,
                            GL.GL_CODE_COMBINATIONS gl_cc,
                            HR.PER_ALL_PEOPLE_F  Req_Emp,
                            HR.PER_ALL_ASSIGNMENTS_F Req_Emp_Assign,
                            HR.hr_all_organization_units Req_Emp_Org,
                            HR.pay_cost_allocation_keyflex Req_Emp_CC
                WHERE
                            PO_RDA.CODE_COMBINATION_ID = GL_CC.CODE_COMBINATION_ID and
                            PO_RLA.REQUISITION_LINE_ID = PO_RDA.REQUISITION_LINE_ID AND
                            PO_RLA.to_person_id = Req_Emp.PERSON_ID AND
                            PO_RLA.REQUISITION_HEADER_ID = PO_RHA.REQUISITION_HEADER_ID AND
                            (trunc(PO_rla.CREATION_DATE) between Req_Emp.effective_start_date and Req_Emp.effective_end_date OR
                            Req_Emp.effective_start_date IS NULL) AND
                            Req_Emp.PERSON_ID = Req_Emp_Assign.PERSON_ID AND
                            Req_Emp_Assign.organization_id = Req_Emp_Org.organization_id AND
                            (trunc(PO_rla.CREATION_DATE) between Req_Emp_Assign.effective_start_date and Req_Emp_Assign.effective_end_date OR
            Req_Emp_Assign.effective_start_date IS NULL) AND
            Req_Emp_Assign.primary_flag = 'Y' AND
            Req_Emp_Assign.assignment_type = 'E' AND
            Req_Emp_Org.cost_allocation_keyflex_id = Req_Emp_CC.cost_allocation_keyflex_id
    SELECT  DISTINCT
      D.DB2_FDW_MGMT_V.RC_PARENT,
      DT_REQ_ALL.FULL_NAME,
      DT_REQ_ALL.EMP_COMPANY_CODE,
      DT_REQ_ALL.EMP_COST_CENTER,
      PO.PO_VENDORS.VENDOR_NAME,
      PO_PO_HEADERS_ALL2.SEGMENT1,
      PO_PO_HEADERS_ALL2.CREATION_DATE,
      PO_DIST_GL_CODE_COMB.SEGMENT1,
      PO_DIST_GL_CODE_COMB.SEGMENT2,
      PO_PO_HEADERS_ALL2.CURRENCY_CODE,
      PO_INV_DIST_ALL.INVOICE_NUM,
      PO_INV_DIST_ALL.INVOICE_DATE,
      (PO_INV_DIST_ALL.INVOICE_AMOUNT* PO_Rates_GL_DR.CONVERSION_RATE),
      (NVL(to_number(PO_DIST_ALL.AMOUNT_BILLED),0) * PO_Rates_GL_DR.CONVERSION_RATE),
      PO_LINES_LOC.LINE_NUM,
      GL.GL_SETS_OF_BOOKS.NAME,
      CASE
            WHEN TRUNC(PO_PO_HEADERS_ALL2.CREATION_DATE) > PO_INV_DIST_ALL.INVOICE_DATE
            THEN 1
            ELSE 0
        END ,
      PO.PO_REQUISITION_LINES_ALL.LINE_LOCATION_ID,
      TRUNC(PO_PO_HEADERS_ALL2.CREATION_DATE,'WW') + 8 WEEK_Ending
    FROM
      ( SELECT * FROM
          DB2.DB2_FDW_MGMT_V,
          GL.GL_CODE_COMBINATIONS  PO_DIST_GL_CODE_COMB,
          DT_REQ_ALL
        WHERE
              DB2.DB2_FDW_MGMT_V.RC_PARENT  In  ( 'Unavailable','Corp','Commercial'  )
           AND
            CASE
               WHEN PO_DIST_GL_CODE_COMB.SEGMENT2  <>  '1000'
               THEN  PO_DIST_GL_CODE_COMB.SEGMENT1 || PO_DIST_GL_CODE_COMB.SEGMENT2 || '_' || NVL(PO_DIST_GL_CODE_COMB.SEGMENT6,'000')
               WHEN DT_REQ_ALL.EMPMGMTCD IS NOT NULL AND
                    PO_DIST_GL_CODE_COMB.SEGMENT2 = '1000'
               THEN DT_REQ_ALL.EMPMGMTCD     
            END =DB2.DB2_FDW_MGMT_V.MH_CHILD
       )   new_table,
       PO.PO_VENDORS,
      PO.PO_HEADERS_ALL  PO_PO_HEADERS_ALL2,
      AP.AP_INVOICES_ALL  PO_INV_DIST_ALL,
       PO.PO_DISTRIBUTIONS_ALL  PO_DIST_ALL,
      PO.PO_LINES_ALL  PO_LINES_LOC,
      GL.GL_SETS_OF_BOOKS,
      PO.PO_REQUISITION_LINES_ALL,
      PO.PO_LINE_LOCATIONS_ALL,
      AP.AP_INVOICE_DISTRIBUTIONS_ALL  PO_DIST_INV_DIST_ALL,
      APPS.HR_OPERATING_UNITS,
      PO.PO_REQ_DISTRIBUTIONS_ALL,
      SELECT
            FROM_CURRENCY,
            TO_CURRENCY,
            CONVERSION_DATE,
            CONVERSION_RATE
        FROM GL.GL_DAILY_RATES
        UNION
        SELECT Distinct
            'USD',
            'USD',
            CONVERSION_DATE,
            1
        FROM GL.GL_DAILY_RATES
      )  PO_Rates_GL_DR
    WHERE
      ( PO_DIST_GL_CODE_COMB.CODE_COMBINATION_ID=PO_DIST_ALL.CODE_COMBINATION_ID  )
      AND  ( PO_DIST_ALL.LINE_LOCATION_ID=PO.PO_LINE_LOCATIONS_ALL.LINE_LOCATION_ID  )
      AND  ( PO_PO_HEADERS_ALL2.VENDOR_ID=PO.PO_VENDORS.VENDOR_ID  )
      AND  ( PO_PO_HEADERS_ALL2.ORG_ID=APPS.HR_OPERATING_UNITS.ORGANIZATION_ID  )
      AND  ( GL.GL_SETS_OF_BOOKS.SET_OF_BOOKS_ID=APPS.HR_OPERATING_UNITS.SET_OF_BOOKS_ID  )
      AND  ( PO_PO_HEADERS_ALL2.CURRENCY_CODE=PO_Rates_GL_DR.FROM_CURRENCY  )
      AND  ( trunc(PO_PO_HEADERS_ALL2.CREATION_DATE)=PO_Rates_GL_DR.CONVERSION_DATE  )
      AND  ( PO_DIST_ALL.REQ_DISTRIBUTION_ID=PO.PO_REQ_DISTRIBUTIONS_ALL.DISTRIBUTION_ID(+)  )
      AND  ( PO.PO_REQ_DISTRIBUTIONS_ALL.REQUISITION_LINE_ID=PO.PO_REQUISITION_LINES_ALL.REQUISITION_LINE_ID(+)  )
      AND  ( PO_LINES_LOC.PO_HEADER_ID=PO_PO_HEADERS_ALL2.PO_HEADER_ID  )
      AND  ( PO.PO_LINE_LOCATIONS_ALL.PO_LINE_ID=PO_LINES_LOC.PO_LINE_ID  )
      AND  ( PO_DIST_ALL.REQ_DISTRIBUTION_ID=DT_REQ_ALL.DISTRIBUTION_ID(+)  )
      AND  ( PO_DIST_ALL.PO_DISTRIBUTION_ID=PO_DIST_INV_DIST_ALL.PO_DISTRIBUTION_ID(+)  )
      AND  ( PO_INV_DIST_ALL.INVOICE_ID(+)=PO_DIST_INV_DIST_ALL.INVOICE_ID  )
      AND  ( PO_INV_DIST_ALL.SOURCE(+)  'XML GATEWAY'   )
      AND 
       ( NVL(PO_PO_HEADERS_ALL2.CANCEL_FLAG,'N')  'Y'   )
       AND
       ( NVL(PO_PO_HEADERS_ALL2.CLOSED_CODE, 'OPEN')  'FINALLY CLOSED'  )
       AND
       ( NVL(PO_PO_HEADERS_ALL2.AUTHORIZATION_STATUS,'IN PROCESS')  'REJECTED'  )
       AND
       ( TRUNC(PO_PO_HEADERS_ALL2.CREATION_DATE)  BETWEEN TO_DATE('01-jan-2011') AND TO_DATE('04-jan-2011')  )
       AND
       PO_Rates_GL_DR.TO_CURRENCY  =  'USD'
      

  • Date in sql query problem

    Hi,
    I have a search form with 1 field (date picker) - the user chooses a date and a report based on a sql query is shown.
    I want the report to be based on only the month and year, and not the particular day.
    If there is a date picker (or something similar) for only month and/or year, then I can change my form, but I don't see this option.
    So, I'm trying to write my query to ignore the Day portion in the search form and just do a search based on the month and year, but i'm having trouble with this.
    This is my query...
    select d.dept, count(e.emp_id) "No. of Employees"
    from dept d, employees e
    where e.date_created = trunc(:P13_DATE, 'MONTH YYYY')
    and d.dept_id = e.dept_id
    group by dept
    order by dept
    How do I write the where clause so that the search is done only on month and year?
    Or otherwise, how can I change the search form to exclude the day from the date?
    Thanks.

    Hi,
    Oh, the invalid number is the result of :P13_DATE being a string value. all item values are actually strings (or varchar2 if you like) when you referencing them with ':Px_ITEM' format. With the pl/sql function there are 2 possible ways to reference item, namely the function: V('Px_ITEM') and NV('Px_ITEM'). Although in SQL varchar2 => number conversion can be dealed with by the SQL engine.
    Unfortunally there is no pl/sql method for getting a DATE of an date-picker item (based on its format mask etc.). Patrick Wolf has added this function in his ApExLib framework, function DV. I find this a nice extension.

  • SQL Query Problem - Please Help

    Post Author: nmellick
    CA Forum: Data Connectivity and SQL
    Hello,
    I am trying to use a query in CR9 to pull the latest date of a DREXAM for each patient.  The patient can have one item or several items.  When I run this query, it only pulls back one record, the latest DREXAM from the whole table, not by patients.  I need it by patients (tracking_id is the patient_id).  Any ideas on what I'm doing wrong?
    Here is the query:select t.tracking_id, t.tracking_group_cd, t.track_event_id, t.requested_dt_tm, t.complete_dt_tm, te.display_keyfrom V500.TRACKING_EVENT t, v500.track_event tewhere t.track_event_id = te.TRACK_EVENT_IDand te.display_key = 'DREXAM'and t.complete_dt_tm = (select max(complete_dt_tm) "MaxDate" from V500.TRACKING_EVENT t, v500.track_event te                        where t.track_event_id = te.TRACK_EVENT_ID                        and te.display_key = 'DREXAM');
    Note:  The tracking_id field shows by patient.  When I run everything up to the last "and" (the complete date), it pulls all rows, which may be more than one per patient.  Basically, I just want the latest DREXAM row per patient.
    Thanks!

    Try to escape the special character '%' using '\%'.

  • Sql query problem which causes crystal reports in visual studio to freeze

    Anyone know why this query posted here freezes up? if i remove  s.enddate IS NULL from the query is when it freezes up. This is used on an infinite campus database for which i only have read only access so no posting anything that requires write access please!
    IT may just be a flaw in my query which it has been before but it only stops responding if i remove the above query and it only started this after i added the comments subreport if i remove it then the action above doesn't cause it to freeze in visual studio.
    I do have a subreport for comments that is in the report too. Heres the main query:
    SELECT Distinct sc.name,sc.address,sc.city,sc.state,sc.zip,sc.phone,gt.name AS Task, ca.StartDate,
    ca.EndDate, s.lastname','s.firstname AS Student, s.studentnumber,e.grade,t.name AS Term,
    gs.score AS [Current Grade],cg.Cumgpa AS GPA,c.name '-'c.number As Course, se.teacherdisplay,gs.personid,
    MAX(CASE WHEN hl.enddate IS NULL AND ccs.guardian = 1 AND ccs.relatedBy = 'Household' AND ccs.mailing = 1 THEN ccs.addressline1 END) AS AddressLine1,
    MAX(CASE WHEN hl.enddate IS NULL AND ccs.guardian = 1 AND ccs.relatedBy = 'Household' AND ccs.mailing = 1 THEN ccs.addressline2 END) AS [City/State],gs.personid
    FROM GradingScore gs
    LEFT JOIN dbo.student s ON s.personid = gs.personid
    JOIN v_CensusContactSummary ccs ON ccs.personid = s.personid
    JOIN dbo.enrollment e ON e.enrollmentid = s.enrollmentid AND e.calendarid = gs.calendarid
    LEFT JOIN dbo.Term t ON t.termid = gs.termid
    JOIN dbo.section se ON se.sectionid = gs.sectionid
    JOIN v_CumGPA cg on cg.personID = s.personID aND cg.calendarID = s.calendarID
    JOIN gradingtask gt ON gt.taskid = gs.taskID
    JOIN dbo.course c ON c.courseid = se.courseid
    JOIN dbo.roster r ON r.sectionid = se.sectionid
    JOIN calendar ca ON ca.calendarID = gs.calendarID
    JOIN School sc ON sc.schoolID = ca.schoolid
    LEFT JOIN householdlocation hl ON hl.householdid = ccs.householdid
    --Change Term Name to match term name needed or if in a report turn it into a Parameter
    WHERE s.enddate IS NULL AND gs.calendarID IN
    (select calendarid
    from dbo.calendar c
    JOIN dbo.schoolyear sy on sy.endyear = c.endyear
    WHERE  c.schoolID = 2)
    GROUP BY s.studentnumber,s.lastname, s.firstname,e.grade, t.name, gt.name, gs.score, cg.cumgpa, c.name, c.number, se.teacherdisplay, ca.startDate, ca.enddate,
    sc.name, sc.address, sc.city, sc.state, sc.zip, sc.phone,gs.personid
    order by [student],[Term],[Course]
    Edited by: jeffman2 on Oct 6, 2011 3:40 PM
    Edited by: jeffman2 on Oct 6, 2011 3:41 PM
    Edited by: jeffman2 on Oct 6, 2011 3:53 PM
    Edited by: jeffman2 on Oct 6, 2011 3:56 PM
    Edited by: jeffman2 on Oct 6, 2011 3:56 PM

    What happens if you try
    SELECT Distinct sc.name,sc.address,sc.city,sc.state,sc.zip,sc.phone,gt.name AS Task, ca.StartDate,
    ca.EndDate, s.lastname+','+s.firstname AS Student, s.studentnumber,e.grade,t.name AS Term,
    gs.score AS Current Grade,cg.Cumgpa AS GPA,c.name +'-'+c.number As Course, se.teacherdisplay,gs.personid,
    MAX(CASE WHEN hl.enddate IS NULL AND ccs.guardian = 1 AND ccs.relatedBy = 'Household' AND ccs.mailing = 1 THEN ccs.addressline1 END) AS AddressLine1,
    MAX(CASE WHEN hl.enddate IS NULL AND ccs.guardian = 1 AND ccs.relatedBy = 'Household' AND ccs.mailing = 1 THEN ccs.addressline2 END) AS City/State,gs.personid
    FROM GradingScore gs
    LEFT JOIN dbo.student s ON s.personid = gs.personid
    JOIN v_CensusContactSummary ccs ON ccs.personid = s.personid
    JOIN dbo.enrollment e ON e.enrollmentid = s.enrollmentid AND e.calendarid = gs.calendarid
    LEFT JOIN dbo.Term t ON t.termid = gs.termid
    JOIN dbo.section se ON se.sectionid = gs.sectionid
    JOIN v_CumGPA cg on cg.personID = s.personID aND cg.calendarID = s.calendarID
    JOIN gradingtask gt ON gt.taskid = gs.taskID
    JOIN dbo.course c ON c.courseid = se.courseid
    JOIN dbo.roster r ON r.sectionid = se.sectionid
    JOIN calendar ca ON ca.calendarID = gs.calendarID
    JOIN School sc ON sc.schoolID = ca.schoolid
    join (select calendarid
           from dbo.calendar c
           JOIN dbo.schoolyear sy on sy.endyear = c.endyear
           WHERE c.schoolID = 2) ci
           on  gs.calendarID  = ci.calendarid
    LEFT JOIN householdlocation hl ON hl.householdid = ccs.householdid
    --Change Term Name to match term name needed or if in a report turn it into a Parameter
    --WHERE s.enddate IS NULL
    GROUP BY s.studentnumber,s.lastname, s.firstname,e.grade, t.name, gt.name, gs.score, cg.cumgpa, c.name, c.number, se.teacherdisplay, ca.startDate, ca.enddate,
    sc.name, sc.address, sc.city, sc.state, sc.zip, sc.phone,gs.personid
    order by student,Term,Course
    Ian

  • SQL query problem with sorting

    Hi,
    I have question regarding sql query . Right now I am getting the results like this if i use this sql query
    select ID,Name,Desc,Priority from emp order by Priority ;
    Priority is varchar field. I don't want to change the Priority field and cannot add a new column in the table. Because i don't have permission to do that.
    ID Name Desc Priority
    =============================================
    234 paul paul desc Highest
    3452 mike mike desc High
    4342 smith smith desc Low
    6565 kelly kelly desc Low
    9878 nate nate desc Medium
    3223 deb deb desc High
    ============================================
    I need a query to get the results like that.
    ID Name Desc Priority
    =============================================
    234 paul paul desc Highest
    3452 mike mike desc High
    3223 deb deb desc High
    9878 nate nate desc Medium
    4342 smith smith desc Low
    6565 kelly kelly desc Low
    ============================================
    If any one knows about this one, please let me know.
    Thanks,
    Bala

    You are aware that there are differences in the SQL implementation between Sqlserver and Oracle? You could try something like this, if there's a INSTR function:
    ORDER BY INSTR('Highest,High,Medium,Low,', Priority || ',')You may have to change the "Priority || ," to a "Priority + ','), if string concatenation is done differently in sqlserver. Don't know about the ('), maybe you need (").
    C.

  • SQL query to select maximum

    Dear all,
    I have a table called "Orders" for a webshop that contains order ID, product ID, product quantity and price per unit. To insert a new order I want to get the highest order ID first and increase it by one, to be used as the new order ID.
    Here is the code:
    String orderIDquery = "SELECT MAX(OrderID) FROM Orders";
              int orderID = 0;
              try
                   rst = stm.executeQuery(orderIDquery);
                   if(rst == null)
                        orderID = 1;
                   else
                        rst.next();
                        orderID = rst.getInt("OrderID");
                        orderID++;
              catch(SQLException e)
                   out.println(e.toString());     
              out.println(orderID);For some reason, I get the SQL exception "column not found" from the "getInt" command, although the column by the name "OrderID" is clearly present in the table.
    Any ideas what could be wrong?
    TIA,
    NetWundi

    Dear all,
    I have a table called "Orders" for a webshop that
    contains order ID, product ID, product quantity and
    price per unit. To insert a new order I want to get
    the highest order ID first and increase it by one, to
    be used as the new order ID.
    Here is the code:
    String orderIDquery = "SELECT MAX(OrderID) FROM Orders";[snip]
    For some reason, I get the SQL exception "column not
    found" from the "getInt" command, although the column
    by the name "OrderID" is clearly present in the
    table.
    Any ideas what could be wrong?You don't have a column named "OrderID" in that Query. You can either refer to the column by number (1) or alias it in your sql and refer to it by the alias name (SELECT MAX(OrderID) AS SomeColumnName FROM Orders".
    Good Luck
    Lee
    >
    TIA,
    NetWundi

  • Selecting both a aggregate function and another field

    I am trying to do something very simple but I am not sure of the syntax.
    I would like to select all of the petid's and find the count of the pets in a given city, both from the same table, Pets.
    Can somebody please help me with this?
    Thanks

    Hi,
    An aggregate function will give you one row of output per group.
    For example, if you use the aggregate COUNT function to get the total number of rows in a whole table, then you can only have one row of output, representing the whole table, so, if I understand the problem, you can't (easily) use an aggregate function.
    Almost all of the aggregate functions have analytic counterparts, that can produce the same results without collapsing the result set into one row per group.
    I think this is what you requested:
    SELECT  petid
    ,       COUNT (*) OVER (PARTITION BY 1)  AS total_cnt
    FROM    pets
    WHERE   city    = 'Paris'  -- or whatever
    ;Sorry, I'm not at a database now, so I can't check, but I think you don't need the PARTITION BY clause, so you can also say:
    ,       COUNT (*) OVER ()  AS total_cntThe keyword OVER marks this as an analytic, rather than an aggregate, function.

Maybe you are looking for

  • How do I get a replacement for a broken phone when I did not have insurance on it?

    So my phone apparently got some dust and dirt in it. Tried to clean it out with a qtip and rubbing alcohol, but to no avail. It was literally sitting on my desk still doing things like buttons were pushed. There is nothing to be done about it, it's p

  • Downloaded PSE 9, photo mail stopped working in PSE 7, help!

    With some trouble I was able to download trial version PSE 9.  I already had PSE 7.  I attempted to e-mail pics using photo mail in PSE 9.  I had to select e-mail system and it would send a confirmation number.  No number arrived.  Went back to PSE 7

  • Import individual schema from data base in 11g

    Hi DBA Gurus, I have 10.0.2 database.i want migrate database from 10.0.2 to 11g.I create dump file by export database from 10.0.2.So i want to import individual schemas(not all schema's at a time) from dump file.If it is possible,could u please guide

  • Watching for changes to the filesystem?

    Hi, Is there an automator object that will allow me (through Applescript perhaps) to receive notifications of when something in a certain part of the filesystem changes? For example, I would like to be notified when a new document is added to the Doc

  • Importing a Webpage

    Is it possible to import a webpage (one that I already published with Adobe Pagemill) into iWeb and edit it?