Update in a Case statement

hi
I have a case statement as
SELECT BB.ID,
CASE WHEN BB.TITLE != AA.PREFIX THEN AA.PREFIX ELSE NULL END "PREFIX",
CASE WHEN BB.LST_NAME != AA.SPRIDEN_LAST_NAME THEN AA.LAST_NAME ELSE NULL END "LAST_NAME",
     CASE WHEN BB.FST_NAME != AA.FIRST_NAME THEN AA.FIRST_NAME ELSE NULL END "FIRST_NAME",
FROM NAME1 BB, NAME2 AA WHERE NAME1.ID = AA.NAME2.ID
I would like to take the results into a new table NAME3
with coulumns NAME_ID,NAME_PREFIX,NAME_LAST_NAME,NAME_FIRST_NAME
like CASE WHEN WHEN BB.TITLE != AA.PREFIX THEN (UPDATE TABLE NAME3 SET name_prefix= AA.PREFIX WHERE NAME1.ID=NAME.ID)
please help me with the syntax

Hi,
If you are updating Name3 then you can use the below query
UPDATE table NAME3 NAME3
   SET (NAME_ID,NAME_PREFIX,NAME_LAST_NAME,NAME_FIRST_NAME) =
SELECT BB.ID,
CASE WHEN BB.TITLE != AA.PREFIX THEN AA.PREFIX ELSE NULL END "PREFIX",
CASE WHEN BB.LST_NAME != AA.SPRIDEN_LAST_NAME THEN AA.LAST_NAME ELSE NULL END "LAST_NAME",
CASE WHEN BB.FST_NAME != AA.FIRST_NAME THEN AA.FIRST_NAME ELSE NULL END "FIRST_NAME",
FROM NAME1 BB, NAME2 AA WHERE NAME1.ID = AA.NAME2.ID AND NAME1.ID = NAME3.id)If you are inserting into NAME3, then please search on the net for "Multitable Insert ALL".
Regards
Aks

Similar Messages

  • Decode and case statement in the update..

    Its is more to it, but I want to check with you guys, the experts on this, this look busy to me, it should be a more simplify way of doing it, do you think will work
    The government decide to change the ethnic codes, and we have to come with certain rules to in our report, anyway, do you think this will work? again It is more to it I declare my variables, this is just one part of the precedure.
    BEGIN
          UTL_FILE.fclose_all;
          v_file_handle := UTL_FILE.fopen (v_out_path, v_out_file, 'a');
          UTL_FILE.put_line (v_file_handle,
                             CHR (10) || TO_CHAR (SYSDATE, 'DD-MON-YYYY HH:MI:SS')
          UTL_FILE.put_line (v_file_handle, 'Entering  spbpers_update');
          SELECT upd_spbpers_upd_cur IS
              spriden_pidm,
              szscapp_birth_state,
              szscapp_birth_city,
              DECODE(szscapp_hisp_or_latino_ind,Y,'2',N,'1'),
              DECODE(szscapp_hisp_or_latino_options,XCM,'2',CUB,'2',MEX,'2',PRI,'2',XSM,'2',ESP,'2',XOH,'2'),  
              DECODE(szscapp_amer_indn_alaska_opt,XAN,'1','1',XCW,'1',XCH,'1',XCK,'1',XNV,'1',XSX,'1'),         
              DECODE(szscapp_amer_indn_alaska_other,XON,'1') (,IND,'1',JPN,'1',KOR,'1',PAK,'1',PHL,'1',VNM,'1',XEA,'1',XIS,'1',XSA,'1'),  
              DECODE(szscapp_asian_options,IND,'1',JPN,'1',KOR,'1',PAK,'1',PHL,'1',VNM,'1',XEA,'1',XIS,'1',XSA,'1'),   ,          
              DECODE(szscapp_other_east_asia,(IND,'1',JPN,'1',KOR,'1',PAK,'1',PHL,'1',VNM,'1',XEA,'1',XIS,'1',XSA,'1'),            
              DECODE(szscapp_other_indian_subcont,XIS,'1'),    
              DECODE(szscapp_other_southeast_asia,XSA,'1'),   
              DECODE(szscapp_blk_or_afr_amer_opt,XAA,'1',XAF,'1',XCB,'1',XOA,'1'),     
              DECODE(szscapp_blk_or_afr_amer_other,XOA,'1'),   
              DECODE(szscapp_natve_hawaian_options,GUM,'1',XHI,'1',ASM,'1',XOP,'1'), 
              DECODE(szscapp_hawaiian_other,XOP,'1'),             
              DECODE(szscapp_white_options,XEU,'1',XME,'1',XOW,'1'),           
              DECODE(szscapp_white_other(XOW,'1')
         FROM
             saturn_midd.szscapp 
         WHERE
         spriden_id =  szscapp_id
         AND  spriden_ntyp_code = 'CAPL'
       IF upd_spbpers_upd_cur%ISOPEN
          THEN
             CLOSE upd_spbpers_upd_cur;
          END IF;
          OPEN upd_spbpers_upd_cur;
          LOOP
             FETCH upd_spbpers_upd_cur
              INTO v_pidm,v_birth_state,v_birth_city,v_latino_ind,v_latino_options,
                   v_indn_alaska_opt,v_indn_alaska_other,v_asian_options,
                   v_other_east_asia,v_other_indian_subcont,v_other_southeast_asia,
                   v_blk_or_afr_amer_opt,v_blk_or_afr_amer_other,v_natve_hawaian_options,           
                   v_hawaiian_other,v_white_options,v_white_other;
             EXIT WHEN upd_spbpers_upd_cur%NOTFOUND; 
             IF upd_spbpers_upd_cur%FOUND
               UPDATE  saturn.spbpers
                           set SPBPERS_ETHN_CODE  = CASE
                   WHEN v_latino_ind            IS NOT NULL THEN (spbpers_ethn_code = v_latino_ind,spbpers_activity_date = sysdate)     
                   WHEN v_latino_options        IS NOT NULL THEN (spbpers_ethn_code = v_latino_options,spbpers_activity_date = sysdate)
                   WHEN v_indn_alaska_opt       IS NOT NULL THEN (spbpers_ethn_code = v_indn_alaska_opt,spbpers_activity_date = sysdate)
                   WHEN v_indn_alaska_other     IS NOT NULL THEN (spbpers_ethn_code = v_indn_alaska_other,spbpers_activity_date = sysdate)
                   WHEN v_asian_options         IS NOT NULL THEN (spbpers_ethn_code = v_asian_options,spbpers_activity_date = sysdate)
                   WHEN v_other_east_asia       IS NOT NULL THEN (spbpers_ethn_code = v_other_east_asia,spbpers_activity_date = sysdate)             
                   WHEN v_other_indian_subcont  IS NOT NULL THEN (spbpers_ethn_code = v_other_indian_subcont,spbpers_activity_date = sysdate)
                   WHEN v_other_southeast_asia  IS NOT NULL THEN (spbpers_ethn_code = v_other_southeast_asia,spbpers_activity_date = sysdate)
                   WHEN v_blk_or_afr_amer_opt   IS NOT NULL THEN (spbpers_ethn_code = v_blk_or_afr_amer_opt,spbpers_activity_date = sysdate)
                   WHEN v_blk_or_afr_amer_other IS NOT NULL THEN (spbpers_ethn_code = v_blk_or_afr_amer_other,spbpers_activity_date = sysdate)
                   WHEN v_natve_hawaian_options IS NOT NULL THEN (spbpers_ethn_code = v_natve_hawaian_options,spbpers_activity_date = sysdate)
                   WHEN v_hawaiian_other        IS NOT NULL THEN (spbpers_ethn_code = v_hawaiian_other,spbpers_activity_date = sysdate)
                   WHEN v_white_options         IS NOT NULL THEN (spbpers_ethn_code = v_white_options,spbpers_activity_date = sysdate)
                   WHEN v_white_other           IS NOT NULL THEN (spbpers_ethn_code = v_white_other,spbpers_activity_date = sysdate)
                   WHEN v_birth_state           IS NOT NULL THEN (spbpers_stat_code_birth = v_birth_state,spbpers_activity_date = sysdate)
                   WHEN v_birth_city            IS NOT NULL THEN (spbpers_city_birth = v_birth_city,spbpers_activity_date = sysdate)
                   WHERE spbpers_pidm = v_pidm;
                  END
                     END IF;
          END LOOP;

    Did the procedure compile ?
    Doesn't look like a right Decode syntax.
    DECODE (col1,'VAL1','This','VAL2','That','ElseThis')
    means
    --Psuedocode
    IF col1 = 'VAL1' THEN 'This'
    IF col1 = 'VAL2' THEN 'That'
    ELSE 'ElseThis'You can use CASE statement Instead of DECODE
    CASE
    when      szscapp_amer_indn_alaska_other
         in ('XON','IND','JPN','KOR','PAK' ..... )  THEN '1'
    when      szscapp_hisp_or_latino_options
         in ('XCM','CUB','MEX','PRI','XSM','ESP','XOH' ...) THEN '2'
    END  SS

  • Using Case statement to insert,update,delete  the tables

    Hi All,
    I have to check the databse ,
    if it is developement then
    insert/update/delete values in tables;
    if it staging then
    insert/update/delete values in tables;
    if it is production then
    insert/update/delete values in tables;
    thers is function available to check the current database
    For doing the about i am trying to write CASE statement like this
    SELECT function,
    case
    when fun = 'developement' then insert into table1 values ('abcd','1234')
    when fun = 'staging' then insert into table1 values ('abcd','1234')
    when fun= 'production' then insert into table1 values ('abcd','1234')
    else null
    from dual
    its throughing me an error
    please help
    Thanks,

    Hi,
    You can use CASE staement any place where an expression is expected.
    For example, in:
    UPDATE  table_a
    SET     col1 = exp1
    ,       col2 = exp2
    WHERE   exp3 = exp4;all the expressions are labled lke expn.
    Note that table_a, col1 and col2 are not expressions: you must hard-code these names, or use dynamic SQL.
    So it's okay to say:
    UPDATE  table_a
    SET     col1 = CASE
                       WHEN  db = 'development'  THEN  0
                       WHEN  db = 'staging'      THEN  1
                   END
    ,       col2 = CASE
                       WHEN  db = 'development'  THEN  NULL
                       WHEN  db = 'staging'      THEN  col2
                   END
    WHERE   db != 'production';In this example:
    in the development database, col1 is set to 0 and col2 is set to NULL
    in the staging database, col1 is set to 1 and col2 is unchanged (that is, set to what it already was)
    in the production database, nothing is changed (the WHERE condition is always FALSE)

  • Update using CASE statement

    Hi
    I have two tables
    employee
    empid empname empaddress valid
    Employeedetails
    empid empname manager
    I would like to validate empname from both the tables using case statement and empid as join and update 'valid' column in employee table to y/n.
    Please help me with the syntax

    Hi,
    Depending on your requirements:
    UPDATE     employee  e
    SET     valid       = (
                     SELECT  CASE 
                                     WHEN  COUNT (*) = 0
                           THEN  'n'
                           ELSE      'y'
                                 END
                     FROM    employeedetails
                     WHERE   empname     = e.empname
    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.
    If you're asking about a DML statement, such as UPDATE, the sample data will be the contents of the table(s) before the DML, and the results will be state of the changed table(s) when everything is finished.
    Explain, using specific examples, how you get those results from that data.
    Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
    See the forum FAQ {message:id=9360002}

  • Update with case statement problem.

    Hi,
    I have this statement
    update tab_tr set col_rate =
      case
      when col_ern_type in ('031','035','036') then (1.5 * col_rate)
      when col_ern_type in ('041','045','046') then (2 * col_rate)
    end;this statement updated some 2 million rows in the table tab_tr. But the total count of rows for col_ern_type in ('031','035','036', '041','045','046') yeild only around 222642 rows.
    select count(*) from tab_tr where col_ern_type in ('031','035','036', '041','045','046');  --> 222642 rowswhat is the problem with the above update statement.
    Thank you,

    Hi,
    DBA_1976 wrote:
    ... I thought the case statement conditions are counted as the where condition. But ......A CASE expression just takes the place of some other expression, such as a literal, a function, or a column.
    For example, which rows do you think this should update?
    UPDATE  tab_tr
    SET     col_rate  = 100;It would update all rows, of course.
    How about this statement?
    UPDATE  tab_tr
    SET     col_rate  = column_x;Will it only change the rows where column_x are a certain value, or not NULL, or in any way depend on column_x? No, of course not. It will update all rows.
    How about this statement?
    UPDATE  tab_tr
    SET     col_rate  = function_y (col_ern_type);Will it only change the rows where the fucntion returns a certain value? Will it depend on the value in col_ern_type? No, of course not. It calls the function for each row, and whatever the function returns (even if the function returns NULL), that's what goes into col_rate on each row.
    A CASE expression is just something that you can substitute in place of any other expression, such as the literal 100, or the column column_x, or the function function_y in the statements above. Naturally, the value that gets put into col_rate will depend on what the CASE expression returns, but the behavior of the UPDATE statement as a whole will not.

  • Update statement with case statement

    Hi
    The following code is thorwing an error like
    =====CODE==========
    BEGIN
    UPDATE emp SET SAL = CASE
    WHEN ENAME = 'SCOTT' THEN SAL = 300
    ELSE NULL;
    END CASE;
    END;
    =====ERROR=======
    ORA-06550: line 3, column 32:
    PL/SQL: ORA-00905: missing keyword
    ORA-06550: line 2, column 2:
    PL/SQL: SQL Statement ignored
    ORA-06550: line 5, column 6:
    PLS-00103: Encountered the symbol "CASE" when expecting one of the following:
    ; 1.
    2. BEGIN
    3. UPDATE emp SET SAL = CASE
    4. WHEN ENAME = 'SCOTT' THEN SAL = 300
    5. ELSE NULL;
    Any suggession?
    Regards
    Balaji

    Hi,
    Yes you are right, but it is not working for the multiple case statement like the following code
    BEGIN
    UPDATE emp SET SAL = CASE
    WHEN ENAME='JONES' THEN '4';
    WHEN ENAME='BLAKE' THEN '5'
    WHEN ENAME='CLARK' THEN '6'
    WHEN ENAME='TURNER' THEN '7'
    WHEN ENAME='MILLER' THEN '8'
    WHEN ENAME='MARTIN' THEN '9'
    WHEN ENAME='WARD' THEN '10'
    WHEN ENAME='ADAMS' THEN '11'
    WHEN ENAME='JAMES' THEN '12'
    WHEN ENAME='SMITH' THEN '13'
    ELSE NULL END;
    END;
    The above code show the following error
    ===========ERROR==========
    ORA-06550: line 3, column 29:
    PL/SQL: ORA-00905: missing keyword
    ORA-06550: line 2, column 2:
    PL/SQL: SQL Statement ignored
    ORA-06550: line 4, column 2:
    PLS-00103: Encountered the symbol "WHEN" when expecting one of the following:
    ( begin case declare end exception exit for goto if loop mod
    null pragma raise return select update while with
    1. BEGIN
    2. UPDATE emp SET SAL = CASE
    3. WHEN ENAME='JONES' THEN '4';
    4. WHEN ENAME='BLAKE' THEN '5'
    5. WHEN ENAME='CLARK' THEN '6'
    Regards
    Balaji
    Edited by: 904493 on Jan 13, 2012 4:18 AM

  • Case statement and Decode function both are not working in Select cursor.

    I have tried both the Case statement and Decode function in Select cursor, but both the things are not working. On the other hand both the things work in just select statement.
    See the first column in select (PAR_FLAG), I need to have this evaluated along with other fields. Can you please suggest some thing to make this work. And also I would like to
    know the reason why decode is not working, I heard some where Case statement do not work with 8i.
    Author : Amit Juneja
    Date : 06/20/2011
    Description:
    Updates the Diamond MEMBER_MASTER table with the values from
    INC.MEM_NJ_HN_MEMBER_XREF table.
    declare
    rec_cnt number(12) := 0;
    commit_cnt number(4) := 0;
    cursor select_cur is
    Select DECODE(1,
    (Select 1
    from hsd_prov_contract R
    where R.seq_prov_id = PM.seq_prov_id
    and R.line_of_business = H.line_of_business
    and R.PCP_FLAG = 'Y'
    and R.participation_flag = 'P'
    and SYSDATE between R.EFFECTIVE_DATE AND
    NVL(R.TERM_DATE,
    TO_DATE('31-DEC-9999', 'DD-MON-YYYY'))),
    'Y',
    'N') PAR_FLAG,
    H.SEQ_ELIG_HIST,
    H.SEQ_MEMB_ID,
    H.SEQ_SUBS_ID,
    H.SUBSCRIBER_ID,
    H.PERSON_NUMBER,
    H.EFFECTIVE_DATE,
    H.TERM_DATE,
    H.TERM_REASON,
    H.RELATIONSHIP_CODE,
    H.SEQ_GROUP_ID,
    H.PLAN_CODE,
    H.LINE_OF_BUSINESS,
    H.RIDER_CODE_1,
    H.RIDER_CODE_2,
    H.RIDER_CODE_3,
    H.RIDER_CODE_4,
    H.RIDER_CODE_5,
    H.RIDER_CODE_6,
    H.RIDER_CODE_7,
    H.RIDER_CODE_8,
    H.MEDICARE_STATUS_FLG,
    H.OTHER_STATUS_FLAG,
    H.HIRE_DATE,
    H.ELIG_STATUS,
    H.PREM_OVERRIDE_STEP,
    H.PREM_OVERRIDE_AMT,
    H.PREM_OVERRIDE_CODE,
    H.SEQ_PROV_ID,
    H.IPA_ID,
    H.PANEL_ID,
    H.SEQ_PROV_2_ID,
    H.SECURITY_CODE,
    H.INSERT_DATETIME,
    H.INSERT_USER,
    H.INSERT_PROCESS,
    H.UPDATE_DATETIME,
    H.UPDATE_USER,
    H.UPDATE_PROCESS,
    H.USER_DEFINED_1,
    H.SALARY,
    H.PEC_END_DATE,
    H.REASON_CODE,
    H.PEC_WAIVED,
    H.BILL_EFFECTIVE_FROM_DATE,
    H.BILLED_THRU_DATE,
    H.PAID_THRU_DATE,
    H.SUBSC_DEPT,
    H.SUBSC_LOCATION,
    H.USE_EFT_FLG,
    H.BENEFIT_START_DATE,
    H.SEQ_ENROLLMENT_RULE,
    H.MCARE_RISK_ACCRETION_DATE,
    H.MCARE_RISK_DELETION_DATE,
    H.MCARE_RISK_REFUSED_DATE,
    H.COMMENTS,
    H.USER_DEFINED_2,
    H.USER_DEFINED_3,
    H.RATE_TYPE,
    H.PCPAA_OCCURRED,
    H.PRIVACY_ON,
    H.PCP_CHANGE_REASON,
    H.SITE_CODE,
    H.SEQ_SITE_ADDRESS_ID,
    PM.seq_prov_id rendered_prov
    from hsd_member_elig_history H,
    INC.PCP_REASSIGN_RPRT_DATA P,
    hsd_prov_master PM
    where P.subscriber_id = H.subscriber_id
    and P.rendered_pcp = PM.provider_ID
    and H.elig_status = 'Y'
    and (H.term_date is NULL or H.term_date >= last_day(sysdate))
    order by H.Seq_memb_id;
    begin
    for C in select_cur loop
    rec_cnt := rec_cnt + 1;
    update hsd_member_elig_history
    set term_date = TRUNC(SYSDATE - 1),
    term_reason = 'PCPTR',
    update_datetime = SYSDATE,
    update_user = USER,
    update_process = 'TD33615'
    where seq_elig_hist = C.seq_elig_hist
    and seq_memb_id = C.seq_memb_id;
    INSERT INTO HSD_MEMBER_ELIG_HISTORY
    (SEQ_ELIG_HIST,
    SEQ_MEMB_ID,
    SEQ_SUBS_ID,
    SUBSCRIBER_ID,
    PERSON_NUMBER,
    EFFECTIVE_DATE,
    TERM_DATE,
    TERM_REASON,
    RELATIONSHIP_CODE,
    SEQ_GROUP_ID,
    PLAN_CODE,
    LINE_OF_BUSINESS,
    RIDER_CODE_1,
    RIDER_CODE_2,
    RIDER_CODE_3,
    RIDER_CODE_4,
    RIDER_CODE_5,
    RIDER_CODE_6,
    RIDER_CODE_7,
    RIDER_CODE_8,
    MEDICARE_STATUS_FLG,
    OTHER_STATUS_FLAG,
    HIRE_DATE,
    ELIG_STATUS,
    PREM_OVERRIDE_STEP,
    PREM_OVERRIDE_AMT,
    PREM_OVERRIDE_CODE,
    SEQ_PROV_ID,
    IPA_ID,
    PANEL_ID,
    SEQ_PROV_2_ID,
    SECURITY_CODE,
    INSERT_DATETIME,
    INSERT_USER,
    INSERT_PROCESS,
    UPDATE_DATETIME,
    UPDATE_USER,
    UPDATE_PROCESS,
    USER_DEFINED_1,
    SALARY,
    PEC_END_DATE,
    REASON_CODE,
    PEC_WAIVED,
    BILL_EFFECTIVE_FROM_DATE,
    BILLED_THRU_DATE,
    PAID_THRU_DATE,
    SUBSC_DEPT,
    SUBSC_LOCATION,
    USE_EFT_FLG,
    BENEFIT_START_DATE,
    SEQ_ENROLLMENT_RULE,
    MCARE_RISK_ACCRETION_DATE,
    MCARE_RISK_DELETION_DATE,
    MCARE_RISK_REFUSED_DATE,
    COMMENTS,
    USER_DEFINED_2,
    USER_DEFINED_3,
    RATE_TYPE,
    PCPAA_OCCURRED,
    PRIVACY_ON,
    PCP_CHANGE_REASON,
    SITE_CODE,
    SEQ_SITE_ADDRESS_ID)
    values
    (hsd_seq_elig_hist.nextval,
    C.SEQ_MEMB_ID,
    C.SEQ_SUBS_ID,
    C.SUBSCRIBER_ID,
    C.PERSON_NUMBER,
    trunc(SYSDATE),
    C.TERM_DATE,
    C.TERM_REASON,
    C.RELATIONSHIP_CODE,
    C.SEQ_GROUP_ID,
    C.PLAN_CODE,
    C.LINE_OF_BUSINESS,
    C.RIDER_CODE_1,
    C.RIDER_CODE_2,
    C.RIDER_CODE_3,
    C.RIDER_CODE_4,
    C.RIDER_CODE_5,
    C.RIDER_CODE_6,
    C.RIDER_CODE_7,
    C.RIDER_CODE_8,
    C.MEDICARE_STATUS_FLG,
    C.OTHER_STATUS_FLAG,
    C.HIRE_DATE,
    C.ELIG_STATUS,
    C.PREM_OVERRIDE_STEP,
    C.PREM_OVERRIDE_AMT,
    C.PREM_OVERRIDE_CODE,
    C.SEQ_PROV_ID,
    C.IPA_ID,
    C.PANEL_ID,
    C.SEQ_PROV_2_ID,
    C.SECURITY_CODE,
    SYSDATE,
    USER,
    'TD33615',
    SYSDATE,
    USER,
    'TD33615',
    C.USER_DEFINED_1,
    C.SALARY,
    C.PEC_END_DATE,
    C.REASON_CODE,
    C.PEC_WAIVED,
    C.BILL_EFFECTIVE_FROM_DATE,
    C.BILLED_THRU_DATE,
    C.PAID_THRU_DATE,
    C.SUBSC_DEPT,
    C.SUBSC_LOCATION,
    C.USE_EFT_FLG,
    C.BENEFIT_START_DATE,
    C.SEQ_ENROLLMENT_RULE,
    C.MCARE_RISK_ACCRETION_DATE,
    C.MCARE_RISK_DELETION_DATE,
    C.MCARE_RISK_REFUSED_DATE,
    C.COMMENTS,
    C.USER_DEFINED_2,
    C.USER_DEFINED_3,
    C.RATE_TYPE,
    C.PCPAA_OCCURRED,
    C.PRIVACY_ON,
    C.PCP_CHANGE_REASON,
    C.SITE_CODE,
    C.SEQ_SITE_ADDRESS_ID);
    commit_cnt := commit_cnt + 1;
    if (commit_cnt = 1000) then
    dbms_output.put_line('Committed updates for 1000 records.');
    commit;
    commit_cnt := 0;
    end if;
    end loop;
    commit;
    dbms_output.put_line('Total number of MEMBER_ELIG_HISTROY records inserted : ' ||
    rec_cnt);
    exception
    when others then
    raise_application_error(-20001,
    'An error was encountered - ' || sqlcode ||
    ' -error- ' || sqlerrm);
    end;

    user10305724 wrote:
    I have tried both the Case statement and Decode function in Select cursor, but both the things are not working. Please define what you mean by not working even if your computer screen is near the internet we can't see it.
    You should also look at the FAQ about how to ask a question
    SQL and PL/SQL FAQ
    Particularly *9) Formatting with {noformat}{noformat} Tags* and posting your version.
    know the reason why decode is not working, I heard some where Case statement do not work with 8i.
    Does this mean you are using 8i? Then scalar sub queries - selects within the select list, are not supported, along with CASE in PL/SQL.
    Select DECODE(1,
    * (Select 1
    from hsd_prov_contract R
    where R.seq_prov_id = PM.seq_prov_id
    and R.line_of_business = H.line_of_business
    and R.PCP_FLAG = 'Y'
    and R.participation_flag = 'P'
    and SYSDATE between R.EFFECTIVE_DATE AND
    NVL(R.TERM_DATE,
    TO_DATE('31-DEC-9999', 'DD-MON-YYYY')))*,
    'Y',
    'N') PAR_FLAG,
    >
    exception
    when others then
    raise_application_error(-20001,
    'An error was encountered - ' || sqlcode ||
    ' -error- ' || sqlerrm);
    http://tkyte.blogspot.com/2008/01/why-do-people-do-this.html                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • User input prompt in CASE statement

    I would like to obtain user input via a prompt and use what the user selects in my OBIEE Report case statement.
    For example &START_DATE AND &END_DATE are user inputs:
    CASE when SHIP_DATE BETWEEN &START_DATE AND &END_DATE THEN 1
    Thanks

    Use presentation variables for start and end_dates
    In the criteria tab->SHIP_DATE->click on fx
    on Edit Column Formula->Bin Tab->
    Add Bin->Add button->Variable->Presentation
    Use the presenation variables with with required condition
    Okay then set 1 at Edit Bin Name
    Mark if helps
    Srini VEERAVALLI on Feb 7, 2013 5:23 PM
    Any updates on this?
    Edited by: Srini VEERAVALLI on Feb 20, 2013 4:10 PM

  • Using case statement in merge when matched

    Hi,
    I want to use case statement in the when matched clause of merge statement to ensure that I update only those fields that are undated.
    create table TEST1
    NAME1 VARCHAR2(25),
    NAME2 VARCHAR2(25),
    ID NUMBER not null
    create table TEST2
    ID NUMBER not null,
    ID2 NUMBER not null,
    NAME1 VARCHAR2(25),
    NAME2 VARCHAR2(25)
    merge into test1 t1
    using
    test2 t2
    ON (t1.id = t2.id)
    when matched
    then
    case
    when t1.name1 != t2.name1
    then
    update set t1.name1 != t2.name1
    when t1.name2 != t2.name2
    then
    update set t1.name2 != t2.name2
    else
    null;
    end
    it does not work and raises invalid sql command. Any idea how can I do that?
    Thanks.
    Sajid
    Edited by: 808255 on Nov 12, 2010 4:22 AM

    Hi
    In that case you would have to use multiple statements and you may as well just use UPDATE instead of MERGE. Also, are you sure that you aren't trying to to fix a problem that doesn't actually exist.
    Think about where the execution time is going to come from...
    I would be tempted to do 1 UPDATE like this...
       UPDATE test1 t1
       SET    (t1.name1,
               t1.name2) = (SELECT  t2.name1,
                                    t2.name2
                            FROM    test2 t2
                            WHERE  t1.id = t2.id
                            AND   (t1.name1 != t2.name1
                             OR    t1.name2 != t2.name2))If you get specific performance issue with this, then post an explain plan and trace and I'll have a look.
    I don't this the cost of the update is going to be as great as you think.
    Cheers
    Ben

  • 11g outer join with case statement - strange results.

    Hello All,
    I am experiencing a strange issues in 11g while using case statement.
    I am not able to reproduce this using sample data. Not sure what is wrong.
    I am not narrowing it to say the usage of case statemnt is giving wrong results, but that is my observation when I am doing trail and error testing.
    Here are the details.
    My Version
    SQL> select * from v$version;
    BANNER
    Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production
    PL/SQL Release 11.2.0.2.0 - Production
    CORE    11.2.0.2.0      Production
    TNS for Linux: Version 11.2.0.2.0 - Production
    NLSRTL Version 11.2.0.2.0 - Production
    SQL> My Query
    SELECT *
      FROM (SELECT DISTINCT mf.schedule,
                            mf.cptcode,
                            NVL (mf.modifier, '00') modifier2,
                            CASE
                               WHEN mf.feetype = 'H'
                                AND mf.multiplier IS NOT NULL THEN
                                  '      0.00'
                               WHEN (mf.feetype != 'H'
                                  OR  mf.feetype IS NULL)
                                AND mf.rbrvsvalue IS NOT NULL
                                AND mf.multiplier IS NOT NULL THEN
                                  LPAD ( TRIM (TO_CHAR ( (mf.rbrvsvalue * mf.multiplier) / 100, 9999999.99)), 10)
                               ELSE
                                  NULL
                            END
                               fee
              FROM provider.mpifee mf, mpi_udffee.udffeeactivecptcodes vld
             WHERE mf.schedule = 'SAPG1'
               AND mf.cptcode = vld.cptcode
               AND NVL (mf.modifier, 'NULL') = NVL (vld.modifier, 'NULL')) inline_fee,
           (SELECT arc.schedule col1, arc.procedurecode col2, NVL (arc.modifier, '00') AS col3
              FROM mpi_udffee.udffeeancfeedata arc
             WHERE monthofextract = '201202'
               AND arc.schedule = 'SAPG1'
               AND TRUNC (SYSDATE - 10) BETWEEN arc.recordeffectivedate AND arc.recordterminationdate) inline_data
    WHERE inline_fee.schedule = inline_data.col1(+)
       AND inline_fee.cptcode = inline_data.col2(+)
       AND inline_fee.modifier2 = inline_data.col3(+);
    In the above query the inline view inline_data returns zero rows. but NVL is still getting applied for col3 and I am getting 00 in the results( strange ).
    Results:
    SCHEDULE        CPTCO MODIFIER2  FEE             COL1  COL2  COL3
    SAPG1           49590 00             667.32                  00
    SAPG1           49611 00             781.03                  00
    SAPG1           49905 00             443.79                  00
    SAPG1           50205 00             883.56                  00
    SAPG1           50220 00            1315.15                  00
    SAPG1           50230 00            1638.74                  00
    SAPG1           50234 00            1666.16                  00
    SAPG1           50250 00            1566.14                  00
    SAPG1           50327 00             262.04                  00
    SAPG1           50541 00            1183.31                  00
    SAPG1           50620 00            1156.88                  00
    SAPG1           50650 00            1321.96                  00
    497 rows selected.
    Just the inline view inline_data,
    SQL> SELECT arc.schedule col1, arc.procedurecode col2, NVL (arc.modifier, '00') AS col3
      2            FROM mpi_udffee.udffeeancfeedata arc
      3           WHERE monthofextract = '201202'
      4             AND arc.schedule = 'SAPG1'
      5             AND TRUNC (SYSDATE - 10) BETWEEN arc.recordeffectivedate AND arc.recordterminationdate;
    no rows selectedMuch unusual thing is when I just remove the case statement from the inline view "inline_fee", I am getting right results,
    SELECT *
      FROM (SELECT DISTINCT mf.schedule,
                            mf.cptcode,
                            NVL (mf.modifier, '00') modifier2          <-- Removed Case statement here
              FROM provider.mpifee mf, mpi_udffee.udffeeactivecptcodes vld
             WHERE mf.schedule = 'SAPG1'
               AND mf.cptcode = vld.cptcode
               AND NVL (mf.modifier, 'NULL') = NVL (vld.modifier, 'NULL')) inline_fee,
           (SELECT arc.schedule col1, arc.procedurecode col2, NVL (arc.modifier, '00') AS col3
              FROM mpi_udffee.udffeeancfeedata arc
             WHERE monthofextract = '201202'
               AND arc.schedule = 'SAPG1'
               AND TRUNC (SYSDATE - 10) BETWEEN arc.recordeffectivedate AND arc.recordterminationdate) inline_data
    WHERE inline_fee.schedule = inline_data.col1(+)
       AND inline_fee.cptcode = inline_data.col2(+)
       AND inline_fee.modifier2 = inline_data.col3(+);
    SCHEDULE        CPTCO MODIFIER2  COL1  COL2  COL3
    SAPG1           46730 00
    SAPG1           46735 00
    SAPG1           46748 00
    SAPG1           46760 00
    SAPG1           46942 00
    SAPG1           46945 00
    SAPG1           47015 00
    SAPG1           47125 00
    SAPG1           47350 00
    SAPG1           47505 00
    SAPG1           47553 00interestingly explain plan for both the statements are exactly same,
    SELECT STATEMENT  ALL_ROWSCost: 138  Bytes: 1,078,274  Cardinality: 11,471                                
         9 HASH JOIN RIGHT OUTER  Cost: 138  Bytes: 1,078,274  Cardinality: 11,471                           
              2 PARTITION RANGE EMPTY  Cost: 2  Bytes: 150  Cardinality: 3                      
                   1 TABLE ACCESS FULL TABLE MPI_UDFFEE.UDFFEEANCFEEDATA Cost: 2  Bytes: 150  Cardinality: 3                 
              8 VIEW MPI_UDFFEE. Cost: 135  Bytes: 504,724  Cardinality: 11,471                      
                   7 HASH UNIQUE  Cost: 135  Bytes: 539,137  Cardinality: 11,471                 
                        6 HASH JOIN  Cost: 134  Bytes: 539,137  Cardinality: 11,471            
                             3 TABLE ACCESS FULL TABLE MPI_UDFFEE.UDFFEEACTIVECPTCODES Cost: 13  Bytes: 177,345  Cardinality: 25,335       
                             5 PARTITION LIST SINGLE  Cost: 120  Bytes: 600,600  Cardinality: 15,015  Partition #: 8       
                                  4 INDEX RANGE SCAN INDEX (UNIQUE) REPRICE.PK_MPIFEE Cost: 120  Bytes: 600,600  Cardinality: 15,015  Partition #: 9  Partitions accessed #11Is there anything wrong with the query? If not have anyone come across this issue or posted it as a bug or is there a patch?
    Update:
    when I set the parameter "_complex_view_merging"=false I am getting the right results even with case statement. But I don want to do some thing unsupported.
    Are there any other viable solutions?
    I appreciate the help.
    Thanks,
    G.
    Edited by: Ganesh Srivatsav on Apr 10, 2012 12:37 PM

    Hi Tubby,
    Right, the query transformation is going wrong. Following is from trace,
    SELECT "INLINE_FEE"."SCHEDULE" "SCHEDULE",
           "INLINE_FEE"."CPTCODE" "CPTCODE",
           "INLINE_FEE"."MODIFIER2" "MODIFIER2",
           "INLINE_FEE"."FEE" "FEE",
           "ARC"."SCHEDULE" "COL1",
           "ARC"."PROCEDURECODE" "COL2",
           CASE
              WHEN "ARC".ROWID IS NOT NULL THEN NVL ("ARC"."MODIFIER", '00')
              ELSE NULL
           END
              "COL3"
      FROM (SELECT DISTINCT "MF"."SCHEDULE" "SCHEDULE",
                            "MF"."CPTCODE" "CPTCODE",
                            NVL ("MF"."MODIFIER", :B2) "MODIFIER2",
                            CASE
                               WHEN ("MF"."FEETYPE" = :B3
                                 AND "MF"."MULTIPLIER" IS NOT NULL) THEN
                                  :B4
                               WHEN ( ("MF"."FEETYPE" <> :B5
                                    OR  "MF"."FEETYPE" IS NULL)
                                 AND "MF"."RBRVSVALUE" IS NOT NULL
                                 AND "MF"."MULTIPLIER" IS NOT NULL) THEN
                                  LPAD ( TRIM (TO_CHAR ( "MF"."RBRVSVALUE" * "MF"."MULTIPLIER" / :B6, :B7)), :B8)
                               ELSE
                                  NULL
                            END
                               "FEE"
              FROM "PROVIDER"."MPIFEE" "MF", "MPI_UDFFEE"."UDFFEEACTIVECPTCODES" "VLD"
             WHERE "MF"."SCHEDULE" = 'SAPG1'
               AND "MF"."CPTCODE" = "VLD"."CPTCODE"
               AND NVL ("MF"."MODIFIER", 'NULL') = NVL ("VLD"."MODIFIER", 'NULL')) "INLINE_FEE",
           "MPI_UDFFEE"."UDFFEEANCFEEDATA" "ARC"
    WHERE "INLINE_FEE"."SCHEDULE" = "ARC"."SCHEDULE"(+)
       AND "INLINE_FEE"."CPTCODE" = "ARC"."PROCEDURECODE"(+)
       AND "INLINE_FEE"."MODIFIER2" = CASE
                                         WHEN ("ARC".ROWID(+) IS NOT NULL) THEN NVL ("ARC"."MODIFIER"(+), '00')
                                         ELSE NULL
                                      END
       AND "ARC"."MONTHOFEXTRACT"(+) = '201202'
       AND "ARC"."SCHEDULE"(+) = 'SAPG1'
       AND TRUNC (SYSDATE-10) >= "ARC"."RECORDEFFECTIVEDATE"(+)
       AND TRUNC (SYSDATE-10) <= "ARC"."RECORDTERMINATIONDATE"(+)Does this refer to a specific bug?
    Thanks,
    G.

  • Update query with case

    my table : workingdate
    sno name startdate
    1 ss 1-12-2011
    2 bb 1-11-2011
    I can update name or start date or both .i will pass new date,name to update through front end.
    I need to validate the condition in case statement i.e. when the new date passed check whether it is greater then start date. if it is greater then it should update with new start date.
    if no then it should be update it will old value.
    i using below query
    update workingdate set name='sss',startdate=(
    case
    when
    (TO_DATE('2011-12-10','yyyy-MM-dd') > (select TO_DATE(startdate,'yyyy-MM-dd') from workingdate where sno=1))
    then TO_DATE('2011-12-10','yyyy-MM-dd')
    else
    select TO_DATE(start_date,'yyyy-MM-dd') from workingdate where sno=1
    end
    where sno=1;
    but when i execute the above query it shows me
    Error report:
    SQL Error: ORA-00936: missing expression
    00936. 00000 - "missing expression"
    *Cause:   
    *Action:
    how could i resolve this.......................

    Check this out
    UPDATE workingdate
    SET NAME='sss',
         startdate=(CASE WHEN (TO_DATE('2011-12-10','yyyy-MM-dd') > startdate THEN TO_DATE('2011-12-10','yyyy-MM-dd') ELSE start_date END)
    WHERE sno=1;Cheers
    Kanchana

  • Insert data with Case Statement

    Good Morning,
    I created table:
    CREATE TABLE DWG_LOG
    (     DL_ID_PK NUMBER NOT NULL ENABLE,
         DL_DRWNG_ID_FK"NUMBER,
         DL_REQUESTOR VARCHAR2(400 BYTE),
         DL_PHONE VARCHAR2(40 BYTE),
         DL_DATE_COPIED DATE,
         DL_APPROVER VARCHAR2(400 BYTE),
         DL_NOTES VARCHAR2(100 BYTE),
         DL_REQ_EMAIL VARCHAR2(60 BYTE),
         DL_DATE_DUE DATE,
         DL_PAST_DUE VARCHAR2(400 BYTE))
    The goal is to populate the DL_PAST_DUE field with a 1 if the date is greater than 90 days else leave NULL. With the help of other more senior developers from OTN I have narrowed my logic to using a CASE Statement instead of a FUNCTION. Below is the projected CASE statement that I am trying to use:
    DECLARE
    v_copied_date DWG_LOG.DL_DATE_COPIED%TYPE;
    v_curr_date SYSDATE;
    BEGIN
    SELECT DL_DATE_COPIED INTO v_copied_date
    FROM DWG_LOG
    CASE
    WHEN (v_curr_date - v_copied_date) > 90 THEN
    INSERT INTO DWG_LOG (DL_PAST_DUE) VALUES ('1');
    ELSE
    INSERT INTO DWG_LOG (DL_PAST_DUE) VALUES ('0');
    END CASE;
    END;
    I am getting the following errors when I run this code in SQL*PLus:
    ERROR at line 10:
    ORA-06550: line 10, column 4:
    PL/SQL: ORA-00933: SQL command not properly ended
    ORA-06550: line 7, column 4:
    PL/SQL: SQL Statement ignored
    ORA-06550: line 12, column 4:
    PLS-00103: Encountered the symbol "ELSE" when expecting one of the following:
    begin case declare end exception exit for goto if loop mod
    null pragma raise return select update while with
    <an identifier> <a double-quoted delimite
    ORA-06550: line 14, column 8:
    PLS-00103: Encountered the symbol "CASE" when expecting one of the following:
    if
    PLEASE, point me in the right direction I know my syntax is off I just don't know where. I will continue to research and refine my script.
    HUMBLY SUBMITTED
    Markus

    I APOLOGIZE
    Good Morning, I created table:
    CREATE TABLE DWG_LOG (
    DL_ID_PK NUMBER NOT NULL ENABLE,
    DL_DRWNG_ID_FK"NUMBER,
    DL_REQUESTOR VARCHAR2(400 BYTE),
    DL_PHONE VARCHAR2(40 BYTE),
    DL_DATE_COPIED DATE,
    DL_APPROVER VARCHAR2(400 BYTE),
    DL_NOTES VARCHAR2(100 BYTE),
    DL_REQ_EMAIL VARCHAR2(60 BYTE),
    DL_DATE_DUE DATE,
    DL_PAST_DUE VARCHAR2(400 BYTE))
    [pre/]
    The goal is to populate the DL_PAST_DUE field with a 1 if the date is greater than 90 days else leave NULL. With the help of other more senior developers from OTN I have narrowed my logic to using a CASE Statement instead of a FUNCTION. Below is the projected CASE statement that I am trying to use:
    DECLARE
    v_copied_date DWG_LOG.DL_DATE_COPIED%TYPE;
    v_curr_date SYSDATE;
    BEGIN
    SELECT DL_DATE_COPIED INTO v_copied_date
    FROM DWG_LOG;
    CASE
    WHEN    (v_curr_date - v_copied_date) > 90 THEN
    INSERT INTO DWG_LOG (DL_PAST_DUE) VALUES ('1');
    ELSE
    INSERT INTO DWG_LOG (DL_PAST_DUE) VALUES ('0');
    END CASE;
    END;
    I am getting the following errors when I run this code in SQL*PLus: ERROR at line 10: ORA-06550: line 10, column 4: PL/SQL: ORA-00933: SQL command not properly ended ORA-06550: line 7, column 4: PL/SQL: SQL Statement ignored ORA-06550: line 12, column 4: PLS-00103: Encountered the symbol "ELSE" when expecting one of the following: begin case declare end exception exit for goto if loop mod null pragma raise return select update while with <an identifier> <a double-quoted delimite ORA-06550: line 14, column 8:
    PLS-00103: Encountered the symbol “CASE” when expecting one of the following:
    if                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • CASE statement... problem using it... what have I done to deserve this?

    I'm trying to use a CASE statement in Ora 8.1.7 (with compatible
    set to 8.1.0) and am finding that I cannot compile the
    procedure.
    I'm using the CASE statement in a call to a procedure...
    insert_addr (p_id_number => v_id_number,
    p_addr_type => v_addr_type,
    p_addr_status => v_addr_status,
    p_addr_pref_ind => v_pref_addr_ind,
    p_date_modified =>
    (CASE
    WHEN cmf_rec.hadoc = cnv_constants.nov17_1958
    THEN cmf_rec.doe
    ELSE cmf_rec.hadoc
    END)
    I'm getting "PLS-00103 Encountered the symbol "CASE" when
    expecting one of the following..." error msg when compiling.
    What have I done wrong? Syntax error? Should I change the
    compatible parameter?
    Thanks.

    You can actually use the CASE statement in Pl/Sql, though not like in SqlPlus.
    You have to use dynamic Sql.
    Example
    create or replace procedure test_case1 is
    v_sql varchar2(4000);
    begin
    v_sql := 'update case_test set qual_rule = '||
             '(case '||
             ' when dob < ''01-jan-1902'' then ''100+'' '||
             ' when dob between ''01-jan-1902'' and ''31-dec-1912'' then ''90-99'' '||
             ' when dob between ''01-jan-1912'' and ''31-jan-1932'' then ''70-89'' '||
             ' when dob between ''01-jan-1932'' and ''31-jan-1952'' then ''50-69'' '||
             ' when dob between ''01-jan-1952'' and ''31-jan-1972'' then ''30-49'' '||
             ' when dob between ''01-jan-1972'' and ''31-jan-1984'' then ''< 30'' '||
             ' else ''under age'' '||
             ' end ) ';
    execute immediate v_sql;
    commit;
    end test_case1;

  • Conditional case statement help.!

    Hello Forum Members,
    I have a table with stores order along with order dates and other information. I have a requirement to write a query to get the nominations from that order's table according to the logic mentioned below.
    Nom1 =  Initial order date and next order within 7 days from initial order date then its considered as R1
    Nom2 = next activity within 7 seven on the same ord_id from its R1 date , this goes on as the order dates increases for same  or single ord_no
    Final Rn  is Count (Rn)
    Rn %-- Count(Rn)  / Count Distinct ( ord_no ) * 100
    Example data output:
    ORD_DATE
    ORD_ID
    1_of_x
    2_of_x
    3_of_x
    4_of_x
    5_of_x
    6_of_x
    Final RnX
    Rn%
    7/10/2013
    10095V1
    1
    0
    0
    0
    0
    0
    8/3/2013
    10095V1
    1
    0
    0
    0
    0
    0
    8/8/2013
    10095V1
    0
    1
    0
    0
    0
    0
    8/12/2013
    10095V1
    0
    0
    1
    0
    0
    0
    9/6/2013
    10095V1
    1
    0
    0
    0
    0
    0
    DDL:
    create table xx_ord_noms
    ord_no varchar(30),
    ord_date date,
    ord_id varchar2(30)
    Sample Data:
    INSERT INTO xx_ord_noms (ord_no, ord_date, ord_id) VALUES ('10091', TO_DATE('07/10/2013','MM/DD/YYYY'), '10091');
    INSERT INTO xx_ord_noms (ord_no, ord_date, ord_id) VALUES ('10091', TO_DATE('08/03/2013','MM/DD/YYYY'), '10091');
    INSERT INTO xx_ord_noms (ord_no, ord_date, ord_id) VALUES ('10091', TO_DATE('08/08/2013','MM/DD/YYYY'), '10091');
    INSERT INTO xx_ord_noms (ord_no, ord_date, ord_id) VALUES ('10091', TO_DATE('08/12/2013','MM/DD/YYYY'), '10091');
    INSERT INTO xx_ord_noms (ord_no, ord_date, ord_id) VALUES ('10091', TO_DATE('09/06/2013','MM/DD/YYYY'), '10091');
    commit;
    I was planning to doing something like this but I am not getting the logic for R1 .. R7
    select ord_no,
           ord_date,
           ord_id,
           prev_dt,
           (to_date(ord_date) - to_date(prev_dt)) data_diff,
           case
             when prev_dt is null or
                  (to_date(ord_date) - to_date(prev_dt)) < 7 then
              'R1'
             when (to_date(ord_date) - to_date(prev_dt)) > 7 THEN
              'R2'
             ELSE
              nULL
           END
      FROM (select a.*,
                   (SELECT MAX(tmp2.ord_date)
                      FROM xx_ord_noms tmp2
                     WHERE a.ord_id = tmp2.ord_id
                       AND tmp2.ord_date < a.ord_date) prev_dt
              from xx_ord_noms a);
    Could someone give me advises or suggestions on how we can get the expected output.
    Thanks in advance.

    LAG and LEAD are good when you want to look forward or back a fixed number of rows, but in this case you don't know how far back you'll need to go.
    I've got a solution. it calculates the Rn as a number, not a column position, but you can transform that with CASE statements if you want. I did it in two main steps:
    First I calculated the Rn by comparing the date of the current and previous row. To do that, I generated a row number using the row_number()  analytic function:
    select ord_no,
           ord_date,
           ord_id,
           numrow
    , Rn
    from xx_ord_noms
    model
      partition by (ord_no)
      dimension by (row_number() over (partition by ord_no order by ord_date)  numrow)
      measures (ord_date, 0 Rn, ord_id )
      rules update
        rn[1] = 1,
        rn[ANY] = CASE when trunc(ord_date[cv()]) - trunc(ord_date[cv() - 1])  < 7 then rn[cv()-1]+1 else 1 end
    ORD_NO     ORD_DATE             ORD_ID         NUMROW         RN
    10091      10-Jul-2013 00:00:00 10091               1          1
    10091      03-Aug-2013 00:00:00 10091               2          1
    10091      08-Aug-2013 00:00:00 10091               3          2
    10091      12-Aug-2013 00:00:00 10091               4          3
    10091      06-Sep-2013 00:00:00 10091               5          1
    Then I needed to identify all the rows of each series. I defined firstDt as the date of the first item in the series:
    firstDt[1] = ord_date[cv()]
    firstDt[ANY] = CASE when rn[cv()]= 1 then ord_date[cv()] else firstDt[cv()-1] end
    With that, the FinalRn is just an analytic max(rn) over (partition by firstDt)
    I'm not clear on what R% is. Your descriptions are unclear and I think they're inconsistent.
    select ord_no, ord_date, ord_id
    , Rn, finalRn, 100*finalRn/totCnt PCT1, 100 * totRn/totCnt PCT2
    , totRn
    from xx_ord_noms
    model
      partition by (ord_no)
      dimension by (row_number() over (partition by ord_no order by ord_date)  numrow)
      measures (ord_date, 0 Rn, ord_id, to_date(null) firstDt, 0 finalRn, 0 totRn, 0 totCnt )
      rules upsert all
        rn[1] = 1
      , rn[ANY] = CASE when trunc(ord_date[cv()]) - trunc(ord_date[cv() - 1])  < 7 then rn[cv()-1]+1 else 1 end
      , firstDt[1] = ord_date[cv()]
      , firstDt[ANY] = CASE when rn[cv()]= 1 then ord_date[cv()] else firstDt[cv()-1] end
      , finalRn[ANY] = max(rn) over (partition by firstDt)
      , totCnt[ANY] = count(*) over()
      , totRn[ANY] = count(case when rn = 1 then 1 else null end) over ()
    ORD_NO     ORD_DATE             ORD_ID             RN    FINALRN       PCT1       PCT2      TOTRN
    10091      10-Jul-2013 00:00:00 10091               1          1         20         60          3
    10091      03-Aug-2013 00:00:00 10091               1          3         60         60          3
    10091      08-Aug-2013 00:00:00 10091               2          3         60         60          3
    10091      12-Aug-2013 00:00:00 10091               3          3         60         60          3
    10091      06-Sep-2013 00:00:00 10091               1          1         20         60          3
    Regards,
    David

  • SQL script into a CASE statement ?

    Hy,
    can someone tell me, please, if is it possible insert into a case statement (shell unix script) one or more SQL script ?
    For example :
    case aaa in
    1 )
    sqlplus blabla <<!
    update ...
    insert ...
    2 )
    esac
    Thank you very much !
    Andys

    /unix/sqlplus -s username/pwd @file_name.sql
    This will work on unix prompt. use this in shell script and implement. file_name.sql containts update logic.
    I hope it will solve ur problem.
    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by Andys:
    Hy,
    can someone tell me, please, if is it possible insert into a case statement (shell unix script) one or more SQL script ?
    For example :
    case aaa in
    1 )
    sqlplus blabla <<!
    update ...
    insert ...
    2 )
    esac
    Thank you very much !
    Andys<HR></BLOCKQUOTE>
    null

Maybe you are looking for

  • Bank Details - IT0009

    Dear SAP Experts, I need to assign certain wage types to be given to the employee in cash despite the fact that the employee is paid through a bank transfer or any payment type stated in Infotype 0009. In other words both wage type /557 and /559 appe

  • Typekit sync problem in Photoshop (Suitcase fusion?)

    I am on a Mac OS X 10.9 and all my CC apps are up to date I installed a few desktop fonts from Typekit. They worked fine in Photoshop but after restarting my Mac the fonts were disabled in Photoshop. I then turned file and font sync of/on in CC setti

  • Photoshop CC: Save For Web function does not update filesize previews when I change filetypes

    I recently tried to save some web banners and wanted to optimize for smallest filesize with best looking output, and as I changed filetypes from Gif to Jpeg to PNG, the preview at the bottom of the window that usually updates with estimated filesize

  • Re: Some Tables are missing: Query Builder

    Thank you!!! I had the same problem and this (table.xml) has helped, I can now see the tables in the left. I'm also not able to see any tables in the "Query Builder". I have tried to explore to see if the fix is similar with no luck. Does the Query B

  • 1.0.1 another bug

    In file browser if I press directory up button - I get wheel of death. Home button is working fine.