Better approach for checking column values between two different rows

My requirement is to find best Approach to find difference between column values of two different rows.Below I've mentioned two different
approaches I'm thinking of,but I'd like to know is there any other better approach.
version details
SQL> SELECT *
  2  FROM V$VERSION;
BANNER
Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - 64bit Production
PL/SQL Release 11.1.0.7.0 - Production
CORE    11.1.0.7.0      Production
TNS for Solaris: Version 11.1.0.7.0 - Production
NLSRTL Version 11.1.0.7.0 - ProductionTable creation script
CREATE TABLE R_DUMMY
   (CA_ID VARCHAR2(16) NOT NULL ENABLE,
     CA_VER_NUM NUMBER(4,2) NOT NULL ENABLE,
     BRWR_SHORT_NAME VARCHAR2(25 CHAR),
     sic_code     number,
     FAC_ID VARCHAR2(10) NOT NULL ENABLE
/ insert script
insert into r_dummy (CA_ID, CA_VER_NUM, BRWR_SHORT_NAME, sic_code, FAC_ID)
values ('CA2001/11/0002', 2.00, 'Nandu',1234, 'FA000008');
insert into r_dummy (CA_ID, CA_VER_NUM, BRWR_SHORT_NAME, sic_code, FAC_ID)
values ('CA2001/11/0002', 3.00, 'SHIJU',456, 'FA000008');Desired O/P :
ca_id               fac_id          column_name          previous name          after_modification
CA2001/11/0002          FA000008     BRWR_SHORT_NAME          Nandu               SHIJU
CA2001/11/0002          FA000008     sic_code          1234               456My approach
select      ca_id,fac_id,column_name,
     decode(column_name,'BRWR_SHORT_NAME',lg_brwr,lg_sic) previous_name ,
     decode(column_name,'BRWR_SHORT_NAME',ld_brwr,ld_sic) after_modification
from
     select
               case
                    when ld_brwr != lg_brwr then
                    'BRWR_SHORT_NAME'
                    when ld_brwr != lg_brwr then
                    'sic_code'
               end
          ) column_name,ca_id,fac_id,lg_brwr,ld_brwr,ld_sic,lg_sic
     from     (
          select ca_id,fac_id,lag_brwr,ld_brwr,ld_sic,lag_sic
          from
                    Select      lead(brwr_short_name,1) over(partition by ca_id,fac_id) ld_brwr,
                         lag(brwr_short_name,1) over(partition by ca_id,fac_id) lg_brwr,
                         lead(sic_code,1) over(partition by ca_id,fac_id) ld_sic,
                         lag(sic_code,1) over(partition by ca_id,fac_id) lg_sic,
                         ca_id,fac_id
                    from r_dummy
          where (ld_brwr != lg_brwr or ld_sic != lg_sic)
)2nd Approach :
=============
select      ca_id,fac_id,column_name,
     decode(column_name,'BRWR_SHORT_NAME',lg_brwr,lg_sic) previous_name ,
     decode(column_name,'BRWR_SHORT_NAME',ld_brwr,ld_sic) after_modification
from
     select
               case
                    when ld_brwr != lg_brwr then
                    'BRWR_SHORT_NAME'
                    when ld_brwr != lg_brwr then
                    'sic_code'
               end
          ) column_name,ca_id,fac_id,lg_brwr,ld_brwr,ld_sic,lg_sic
     from     (
          select ca_id,fac_id,brwr_short_name,sic_code
          from
                    Select      ca_id,fac_id,brwr_short_name lg_brwr,sic_code lg_sic
                    from     r_dummy
                    where     ca_ver_num = '2.00'
               )o,(
                    Select      ca_id,fac_id,brwr_short_name ld_brwr,sic_code ld_sic
                    from     r_dummy
                    where     ca_ver_num = '3.00'
                          )n
          where      0.ca_id = n.ca_id
               and 0.fac_id = n.fac_id
               and (ld_brwr != lg_brwr or ld_sic != lg_sic)
)Hi Experts,
     I've provided sample data where I'm checking for just two columns viz brwr_short_name ,sic_code,but in real time
I've to check for 8 more columns so please suggest me with a better approach.
I appreciate your precious suggestions.

Hi,
Thanks for posting the CREATE TABLE and INSERT statements; that really helps!
Here's one wa. Like your 2nd approach, this uses a self-join:
WITH     got_r_num     AS
     SELECT  ca_id
     ,     ROW_NUMBER () OVER ( PARTITION BY  ca_id
                               ,                    fac_id
                         ORDER BY        ca_ver_num
                             )    AS r_num
     ,     brwr_short_name
     ,     TO_CHAR (sic_code)     AS sic_code
     ,     fac_id
--     ,     ...     -- Other columns (using TO_CHAR if needed)
     FROM     r_dummy
,     unpivoted_data     AS
     SELECT     *
     FROM     got_r_num
     UNPIVOT     INCLUDE NULLS
          (    txt
          FOR  column_name IN ( brwr_short_name          AS 'BRWR_SHORT_NAME'
                        , sic_code               AS 'SIC_CODE'
--                        , ...     -- Other columns
SELECT       p.ca_id
,       p.fac_id
,       p.column_name
,       p.txt          AS previous_name
,       a.txt          AS after_modification
FROM       unpivoted_data   p
JOIN       unpivoted_data   a  ON  p.ca_id     = a.ca_id
                       AND p.fac_id     = a.fac_id
                     AND p.column_name     = a.column_name
                     AND p.r_num      = a.r_num - 1
                     AND p.txt || 'X' != a.txt || 'X'
ORDER BY  a.r_num
;To include other columns, add them in the 2 places where I put the comment "Other columns".
Ca_ver_num can have any values, not just 2.00 and 3.00.
This will show cases where a value in one of the columns changed to NULL, or where NULL changed to a value.
There ought to be a way to do this without a separate sub-query like got_r_num. According to the SQL Language manual, you can put expressions in the UPIVOT ... IN list, but when I tried
...     UNPIVOT     INCLUDE NULLS
          (    txt
          FOR  column_name IN ( brwr_short_name          AS 'BRWR_SHORT_NAME'
                             , TO_CHAR (sic_code)     AS 'SIC_CODE'
          )I got the error "ORA_00917: missing comma" right after TO_CHAR. Perhaps someone else can show how to eliminate one of the sub-queries.

Similar Messages

  • Replacing one column value between two rows..help??

    HI,
    I have table T
    it has five columns, all are in number data type
    Col1 and col2 are jointly primary key i.e. they cannot be repeated combined
    when i run this query..
    SQL> Select * from t
    it shows me the data like this
    Col1        Col2              Col3       Col4           Col5
    1             1               78          58            12.76
    2             1               128         446           32.10
    3             1               468         566           52.10
    4             1               878         58            52.05
    5             1               987         348           22.02
    ... so on.
    my requirement is that i want to update this table by replacing the col1 value between any two rows
    suppose this is the first row
    Col1        Col2          Col3        Col4         Col5
    1             1             78          58        12.76
    and this is any 2nd row
    Col1        Col2          Col3        Col4        Col5
    5             1            987         348       22.02
    now i want that for first row the value of col1 replaces the value of col1 of 2nd row
    and for 2nd row the value of col1 replaces the value of col1 of 1st row
    i.e.
    Col1        Col2          Col3        Col4         Col5
    5             1            78           58         12.76
    Col1        Col2          Col3        Col4         Col5
    1             1            987        348          22.02
    please tell how to achieve this in single query/procedureregards,
    Ramis

    SQL> create table t (id1 number, id2 number, name varchar2(1));
    Table created.
    SQL> alter table t add primary key (id1,id2);
    Table altered.
    SQL> insert into t values(1,1,'A');
    1 row created.
    SQL> insert into t values(5,1,'B');
    1 row created.
    SQL> commit;
    Commit complete.
    SQL> select * from t;
           ID1        ID2 N
             1          1 A
             5          1 B
    SQL> var val1 number
    SQL> var val2 number
    SQL> exec :val1 := 1;
    PL/SQL procedure successfully completed.
    SQL> exec :val2 := 5;
    PL/SQL procedure successfully completed.
    SQL> update t set id1 = (:val1 + :val2) - id1 where id1 in (:val1,:val2);
    2 rows updated.
    SQL> select * from t;
           ID1        ID2 N
             5          1 A
             1          1 B
    SQL> rollback;
    Rollback complete.
    SQL> select * from t;
           ID1        ID2 N
             1          1 A
             5          1 B
    SQL> commit;
    Commit complete.
    SQL> update t set id1 = decode(id1,:val1,:val2,:val1)
      2  where id1 in (:val1, :val2);
    2 rows updated.
    SQL> select * from t;
           ID1        ID2 N
             5          1 A
             1          1 BRgds.

  • Swap between two different item categories in sales orders for sub-contracting

    Dear gurus,
    my requirement is to have the ability to swap between two different item categories for sales orders for sub-contracting.
    This should be controlled by a combination of the material and a value maintained the Usage field in the Customer Material Info Record (for example by entering a ‘V’).  A combination of Sales Doc Type, Item Cat Group and Usage should result in the creation of a purchase requisition.
    In the event that a process order is required instead of a purchase requisition (i.e. the product is to be manufactured in-house instead of sub-contracted) the user must have the ability to change the Item Category within the sales order to produce a process order.
    The user would just change the item category within the sales order, and the system would automatically remove the purchase requisition assigned to the SO, and create a process order and assign it to the SO.
    Can you suggest any possible solution?
    Thank you in advance.

    Hi Majlo,
    In my system, I checked.  First created sales order with third party line item and then changed item category to normal item category.
    Till Purchase order not created, I can change Item category of my sales order line item.
    In this case SAP inform by log and once save delete purchase requisition of that line item .
    For this you need to assign another item category as an manual item category in SPRO Item category assignment.
    After this user can manually change item category to other one manually, if PO do not exist.
    Please let me know if your query is different.
    Regards

  • Opening and Closing values on two separate rows for an indvidual A/c?

    Hi / Salam To all SAP Members,
    I am creating a COGS report in which i need to show opening and closing values for a stock account in two separate rows. The tool i am using is report painter.
    What i need to know is how can the system identify between opening and closing values for that account? Which characteristic/s do i need to include in the rows? The table i am using is FAGLFLEXT.
    Please provide help.
    Regards,
    Mohammed Ali Khan.

    Resolved Issue.

  • How to add a new column in between two other columns

    I need to add a new column in between two other existing columns. Does anyone know how to do that? The ALTER statement adds the column at the end. Can someone give an example.
    Thanks
    Murali
    null

    There is no simpler way of doing this because it is not strictly necessary: you can always see your data in the order you want simply by going SELECT col1, col2, col98, col4, etc. Thus the column order only matters when you execute SELECT * FROM...
    If that really is important enough to you you'll have to drop and re-create the table, for which there are a number of different strategies.
    Your final comment suggests that you don't retain your database build scripts. If you did then rebuilding your constraints would be painless. There is a lesson there. The good news is that if you have TOAD (download from www.quest.com) you can generate DDL scripts from your existing schema.
    HTH, APC

  • Awk - printing a value between two matching regex [SOLVED]

    I'm trying to write a script to parse a single line output, but to then only display the value between two matching regex.
    I have got it to only display the value between the matching regex, but then it carries on and displays the rest of the line. How do I tell it to stop once the matching value has been printed?
    ARTIST=`awk '/Artist/,/Artist/ {gsub(/Artist/, Artist); print}' /home/sapphire/.foobar2000/track_info`
    This produces 'Akira Yamaoka Title She Title Album Silent Hill 1 OST Album CurrentTime 0:03 CurrentTime TotalTime 2:01 TotalTime' rather then the desired 'Akira Yamaoka'.
    So I guess I'm asking how one would go about terminating the above awk command? Thanks - I know, it'll be something simple - but I'm not experienced with scripting
    Last edited by wyvern (2008-04-10 11:37:30)

    ibendiben wrote:Could you share the file you are extracting the data from?
    No problem, and thank you for the help so far
    This is what's written each time I update my playing track, no more, no less:
    Artist Akira Yamaoka Artist Title Silent Hill Title Album Silent Hill 1 OST Album CurrentTime 0:04 CurrentTime TotalTime 2:51 TotalTime
    Single line only, as the plugin won't break up the text into anything more than the one line

  • Customize Alert messages for checking duplicate value and Success alert

    Hi All,
    I want to show two alert against the same "Submit" button to--
    1. Alert messages for checking duplicate value and show the Duplicate value found alert and
    2. Success Alert if the form is success to commit and no duplicate value found.
    I did all thing but when alert-1 shows and i pressed the ok button of the alert then the second alert also shows which i don't want to show.
    Which i can do in this issue? Have there anyone to help me!
    Arif

    Hi Manu,
    I have placed the following code
    1. against the Submit button--
    if error_code=40508 then
         commit_form;
    elsif :USERDELETION.CANCELLATION_USERID is not null then
    do_key('COMMIT_FORM');
    else null;
    end if;
    2. Code against the key-commit trigger in the form level--
    commit_form;
    DECLARE
    vAlert NUMBER;
    BEGIN
    set_alert_property('ALERT_TO_VERIFY',ALERT_MESSAGE_TEXT, 'Your Form has successfully submitted and your Reference id is '||:USERDELETION.REF_NO);
    vAlert:=SHOW_ALERT('ALERT_TO_VERIFY');
    END;
    3. Code against the on-error trigger in the form level--
    DECLARE
    vAlert NUMBER;
    BEGIN
         if ERROR_CODE = 40508 then
    set_alert_property('ERROR_ALERT',ALERT_MESSAGE_TEXT, 'This user deletion request has already submitted of the user named '||'"'||:USERDELETION.FULLNAME||'"');
    vAlert:=SHOW_ALERT('ERROR_ALERT');
    elsif
              ERROR_CODE = 40202 then
    set_alert_property('ERROR_ALERT',ALERT_MESSAGE_TEXT, 'Existing userid must be filled-up !');
    vAlert:=SHOW_ALERT('ERROR_ALERT');
    else
                   message(error_type||to_char(error_text)||': '||error_text);
    end if;
    END;
    If there have any confusion, please ask me.
    Arif

  • In BADi , How to pass the values between two Method

    Hi Experts,
    We have two methods in BADis. How to pass the value  between two Methods. Can you guys explain me out with one example...
    Thanks & Regards,
    Sivakumar S

    Hi Sivakumar!
    Create a function group.
    Define global data (there is a similiar menu point to jump to the top include).
    Create one or two function modules, with which you can read and write the global data.
    In your BADI methods you can access the global data with help of your function modules. It will stay in memory through the whole transaction.
    Regards,
    Christian

  • XMLGEN: Produce XML dump of a table WITH tags for null column values

    I am new to generating XML so bear with me....
    We have a customer who needs an XML extract of data, including tags for any column that is null.
    I created a simple test case below using DBMS_XMLGEN.getXML. The first row (A1) has no null values and thus tags for columns A, BEE and CEE are produced. The second row (A2) has null in column BEE and thus tags for only columns A and CEE are produced.
    Is there a way to force a tag for null column BEE in the second row?
    create table foo (A varchar2(10), BEE number, CEE date);
    insert into foo values ('A1',1,sysdate);
    insert into foo values ('A2',null,sysdate);
    SELECT DBMS_XMLGEN.getXML('SELECT * FROM foo') FROM dual;
    <ROWSET>
    <ROW>
    <A>A1</A>
    <BEE>1</BEE>
    <CEE>27-SEP-12</CEE>
    </ROW>
    <ROW>
    <A>A2</A>
    <CEE>27-SEP-12</CEE>
    </ROW>
    </ROWSET>

    What's the database version? (SELECT * FROM v$version)
    Could you use this instead :
    SQL> select xmlserialize(document
      2           xmlelement("ROWSET",
      3             xmlagg(
      4               xmlelement("ROW",
      5                 xmlelement("A", a)
      6               , xmlelement("BEE", bee)
      7               , xmlelement("CEE", cee)
      8               )
      9             )
    10           )
    11         -- for display purpose only :
    12         as clob indent
    13         )
    14  from foo
    15  ;
    XMLSERIALIZE(DOCUMENTXMLELEMEN
    <ROWSET>
      <ROW>
        <A>A1</A>
        <BEE>1</BEE>
        <CEE>2012-09-27</CEE>
      </ROW>
      <ROW>
        <A>A2</A>
        <BEE/>
        <CEE>2012-09-27</CEE>
      </ROW>
    </ROWSET>
    Or,
    SQL> select xmlserialize(document
      2           xmlquery(
      3             '(#ora:view_on_null empty #)
      4             {
      5               <ROWSET>{fn:collection("oradb:/DEV/FOO")}</ROWSET>
      6             }'
      7             returning content
      8           )
      9           as clob indent
    10         )
    11  from dual;
    XMLSERIALIZE(DOCUMENTXMLQUERY(
    <ROWSET>
      <ROW>
        <A>A1</A>
        <BEE>1</BEE>
        <CEE>2012-09-27</CEE>
      </ROW>
      <ROW>
        <A>A2</A>
        <BEE/>
        <CEE>2012-09-27</CEE>
      </ROW>
    </ROWSET>
    (where "DEV" is my test schema)
    If you want to stick with DBMS_XMLGEN, you're gonna have to use PL/SQL and setNullHandling procedure.
    Edited by: odie_63 on 27 sept. 2012 17:14

  • Single column value into two column of report

    Hi frnds,
    I have a column of Adress in my databse table from where i have to fetch values and show it a report
    able to get report but showing in single column if i take a printout paper will be wasted so I thought of passing these values to two different columns
    please help me in giving some suggestions

    In Oracle 9 you can get rid of the regex functions and use traditional SUBSTR, INSTR and REPLACE:
    ABSOLUTELY NOT TESTED...
    SELECT col1,SUBSTR ( ','||col2||',', instr(','||col2||',',',',lvl)+1,instr(','||col2||',',',',lvl+1)-instr(','||col2||',',',',lvl)-1)
      FROM table_name,
           (SELECT LEVEL lvl
              FROM (SELECT MAX (LENGTH (REPLACE ( col2, ',',''))) mx
                      FROM table_name)
            CONNECT BY LEVEL <= mx + 1)
    WHERE lvl - 1 <= LENGTH (REPLACE ( col2, ',',''));Max

  • Globale variable to exchange  value between two planning function (Formel)

    Hi,
    can I define a globale variable to exchange the value between two planning function?
    any anwser will be very appreciated.
    hongwei

    Hi,
    can I define a globale variable to exchange the value between two planning function?
    any anwser will be very appreciated.
    hongwei

  • How to pass value between two forms.

    Hi all,
    how to pass value between two forms(using :parameter),...
    Thanks
    Rajesh

    To use parameters, create a parameterlist with the named parameters
    DECLARE
      pl_id PARAMLIST;
      pl_name VARCHAR2(10) := 'tempdata';
    BEGIN
      pl_id := Get_Parameter_List(pl_name);
      IF not Id_Null(pl_id) THEN
        DESTROY_PARAMETER_LIST(pl_id);
      END IF;
      pl_id := Create_Parameter_List(pl_name);
      ADD_PARAMETER (pl_id,'MYPARAMETER',TEXT_PARAMETER,:BLOCK.VALUE);      
      CALL_FORM('MYNEWFORM', NO_HIDE, DO_REPLACE, NO_QUERY_ONLY, pl_id);
    END;In the new form you can then just access the parameters via :PARAMETER.MYPARAMETER;
    An alternative is the usage of globals:
    :GLOBAL.MYPARAM:=:BLOCK.VALUE;
    -- call the emp-form
    CALL_FORM('MYNEWFORM', NO_HIDE, DO_REPLACE);and in the new form use:
    DEFAULT_VALUE(NULL, 'GLOBAL.MYPARAM');
    IF :GLOBAL.MYPARAM IS NOT NULL THEN
    ...The advantage of gloabls is that they can also return values back to the calling form, which is not possible using parameters

  • Use of SAP memory to transfer data between two different sessions.

    Hello experts,
    I wish to know how to use SAP memory to transfer data between two different sessions.
    The scenario is that when I run a report and change a variable, the value of changed variable should be availabe to another user on another terminal.
    Thanks & Regards!
    Sumit

    Hello,
    Just to add what Max has already mentioned. IMPORT TO / EXPORT FROM DATABASE statements can be used to store data in special "cluster" tables (you can't use any DDIC table) e.g., INDX.
    @OP: You can opt for Shared Memory(SHM) for this specific requirement as well. In my opinion SHM is a bit tricky to code, but it is easier to monitor. The opposite holds true for "data clusters".
    You should remember SHM is app-server specific. So if you've a load balancing scenario, using SHM can cause problems.
    Hope i'm clear.
    BR,
    Suhas
    Edited by: Suhas Saha on Nov 19, 2010 4:12 PM

  • How can I interact between two different frames in the same indesign template as well as from one template to another.

    I am looking for the best way (or any way) to interact between two different frames in the same indesign template as well as from one template to another. It's for a DPS app which needs to carry some button initiated data from one page to another and then present it in a table.

    There is no simple way to do it, as itunes wont let you use it on another computer without wiping the contents first.
    However if you really want to transfer songs to another computer then you could try this;
    * make sure that your ipod is accessible as a disk drive (ipod options)
    * when you plug your ipod into the computer you want to transfer to make sure you select "no" or "cancel" when it asks to wipe the contents. Leave the ipod connected and quit from itunes.
    * go to "my computer" and access the ipod directly. You probably have to select "view hidden files" from windows. You will see a lot of folders with odd names like ZX838aff with similar named files inside.
    * copy these files to a folder on your computers hardrive. Now remove the ipod and start itunes.
    * import the files from the folder you made in the last step.
    * Now your music is on itunes, but with unrecogisable names.
    This is the only way I have found to do it, but there may be another way, say with an application to do the hard work for you.
    Generic homebuild PC Windows XP
    Generic homebuild PC   Windows XP  

  • I would like the share an iTunes library between two different accounts on one Mac. How do I do this?

    iTunes no longer works properly (aka at all) while using one of the user accounts set up on my iMac. It does, however, work when logging in under another user account on the same iMac. (if any of you can help me solve this issue that would be perfect). If there is no solution can anyone help with my request to share an iTunes library between two different accounts on one Mac. How do I do this?

    jc_hering wrote:
    that works for anything he purchases after he creates the new account.  What about his current music that currently resides in my itunes library?  How can I get his current music out of my library into his new account/library??  Thanks..
    Copy it to his computer into his iTunes library and authorize his computer with the iTunes account used to purchase them..
    You cannot tranfser items from one iTunes account to another. Purchased items remain part of the iTunes account is was purchased with.
    iTunes account - used to purchase items
    iTunes library - where purchases (and CD RIPs) go on the computer

Maybe you are looking for

  • BW web report Encoding issue

    Hi Experts, In our company, the BW server is located in China, but Korea data is also merged in our system. We provided different query for China and Korea user. But when we run Korea query report, the default Encoding is Chinese, and even if we chan

  • Comp 3 new user needs help !! (please)

    Not sure which setting to use, have tried MPEG-2 5.0 2 pass and had no audio. Do I need to select audio seperately (eg AIFF 48-16). Anyway, now I can't seem to submit. I've daged and dropped the destination (desktop) and I've draged and droped the so

  • How do you save a report from VB?

    Post Author: calvin CA Forum: .NET How do you save an updated Crystal Report (CRXI) from a VB.Net (2005) program? We're using the ReportDocument object model, not the CrystalViewer & it appears there's a SaveAs method but not Save.Worse, the SaveAs d

  • Terminal - how to find my external hard drive using unix commands

    just discovered terminal and using cd and ls commands, which are the only commands i know, i realized that i can't find my external hard drive. i thought it would be listed on my desktop, as it is in the OSX interface, but it isn't there. not that im

  • Install Oracle 8.1.7 (64 bit) on AIX 5L

    Hi all, I'm installing Oracle 8.1.7 (64 bit) on IBM AIX 5L and everything goes fine while copying files, but there are problems in the relinking phase. I've installed the 32 bit version and it works, so the problem seems to be with the 64 bit version