Compare two rows in the same table

Hi all

I need to compare two rows in the same table, I don't know hoe to do it in pl/sql. Please help me on this.

example:

price of ro TR
xya0001 AMA.7 12
xya0003 ama6 14
xya0004 AMA.7 16

in table b is a unique value for each line, I need to compare the price column and see if the first value is less than or greater than the following value and, if there is more to put the corresponding value of br to a variable, and if it is less, put the corresponding value of the br to another variable. I don't know a method to do this, as I'm new to pl/sql. Please help me in this
for data in(select tr,br,price, lag(price) over ( order by tr) newcol
from yourtable)
loop
if nvl(data.newcol,0) > data.price then
variable1:=data.br;
else
varable2:=data.br;
end if;
end loop;

Tags: Database

Similar Questions

  • COMPARING TWO ROWS IN THE SAME TABLE AND DELETE THEM USING DELETION BLOCK

    Hi all
    I have a problem. I have an Employee table

    employee

    Emp_name Emp_id Emp_status Emp_date

    John 1 P 11-27-2010

    Mike 2 26/11/2010 S

    Simon P 3 22 / 11 / 2010

    Dennis C 4 25/11/2010...


    I compare the rows in the table and their employee_status if 'P', should I remove the... Here, I should delete lines 1 and 3 as their Emp_status is 'P '. I only use BULK DELETE... I tried to use the join query internal and deletion, but it does not work... Can someone help me...

    Ooops, it should be:

    and e2.emp_status in ('P', 'C')

    not

    and e2.emp_status in ('P', 'A')

    Here it goes:

    SQL> select  *
      2    from  employees
      3  /
    
    E EMP_NAME      EMP_KEY          X
    - ---------- ---------- ----------
    C John              123          1
    P Mike              123          2
    P Paul              123          6
    C Harry             124          5
    A Gass              125          7
    C Gass              125          7
    
    6 rows selected.
    
    delete  employees e1
      where 2 = (
                 select  count(distinct e2.emp_status)
                      from  employees e2
                      where e2.emp_key = e1.emp_key
                        and e2.emp_status in ('P','C')
                   )
    /
    
    3 rows deleted.
    
    SQL>
    

    SY.

  • Mr President, how can I enter two rows at the same time with different default values that only the first line to use see?

    Mr President.

    My worm jdev is 12.2.1

    How to enter two rows at the same time with different default values that only the first line to use see?

    Suppose I have a table with four fields as below

    "DEBIT" VARCHAR2(7) , 
      "DRNAME" VARCHAR2(50),
      "CREDIT" VARCHAR2(7) , 
      "CRNAME" VARCHAR2(50),
    

    Now I want that when I click on a button (create an insert) to create the first line with the default values below

    firstrow.png

    So if I click on the button and then validate the second row with different values is also inserted on commit.

    The value of the second row are like the picture below

    tworows.png

    But the second row should be invisible. It could be achieved by adding vc in the vo.

    The difficult part in my question is therefore, to add the second row with the new default values.

    Because I already added default values in the first row.

    Now how to add second time default values.

    Concerning

    Mr President

    I change the code given by expensive Sameh Nassar and get my results.

    Thanks once again dear Sameh Nassar .

    My code to get my goal is

    First line of code is

        protected void doDML(int operation, TransactionEvent e) {    
    
            if(operation != DML_DELETE)
                 {
                     setAmount(getPurqty().multiply(getUnitpurprice()));
                 } 
    
            if (operation == DML_INSERT )
                       {
                               System.out.println("I am in Insert with vid= " + getVid());
                           insertSecondRowInDatabase(getVid(),getLineitem(),"6010010","SALES TAX PAYABLE",
                            (getPurqty().multiply(getUnitpurprice()).multiply(getStaxrate())).divide(100));      
    
                           }
    
            if(operation == DML_UPDATE)
                              {                                                    
    
                                 System.out.println("I am in Update with vid= " + getVid());
                             updateSecondRowInDatabase(getVid(),
                                 (getPurqty().multiply(getUnitpurprice()).multiply(getStaxrate())).divide(100));      
    
                              }                      
    
            super.doDML(operation, e);
        }
        private void insertSecondRowInDatabase(Object value1, Object value2, Object value3, Object value4, Object value5)
                  {
                    PreparedStatement stat = null;
                    try
                    {
                      String sql = "Insert into vdet (VID,LINEITEM,DEBIT,DRNAME,AMOUNT) values " +
                 "('" + value1 + "','" + value2 + "','" + value3 + "','" + value4 + "','" + value5 + "')";  
    
                      stat = getDBTransaction().createPreparedStatement(sql, 1);
                      stat.executeUpdate();
                    }
                    catch (Exception e)
                    {
                      e.printStackTrace();
                    }
                    finally
                    {
                      try
                      {
                        stat.close();
                      }
                      catch (Exception e)
                      {
                        e.printStackTrace();
                      }
                    }
                  }  
    
                  private void updateSecondRowInDatabase(Object value1, Object value5)
                  {
                    PreparedStatement stat = null;
                    try
                    {
                      String sql = "update vdet set  AMOUNT='"+ value5+"' where VID='" + value1 + "'";                     
    
                      stat = getDBTransaction().createPreparedStatement(sql, 1);  
    
                      stat.executeUpdate();
                    }
                    catch (Exception e)
                    {
                      e.printStackTrace();
                    }
                    finally
                    {
                      try
                      {
                        stat.close();
                      }
                      catch (Exception e)
                      {
                        e.printStackTrace();
                      }
                    }                  
    
                  }
    

    Second line code is inside a bean method

        public void addNewPurchaseVoucher(ActionEvent actionEvent) {
            // Add event code here...
    
            BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
                   DCIteratorBinding dciter = (DCIteratorBinding) bindings.get("VoucherView1Iterator");
                   RowSetIterator rsi = dciter.getRowSetIterator();
                   Row lastRow = rsi.last();
                   int lastRowIndex = rsi.getRangeIndexOf(lastRow);
                   Row newRow = rsi.createRow();
                   newRow.setNewRowState(Row.STATUS_NEW);
                   rsi.insertRowAtRangeIndex(lastRowIndex +1, newRow);
                   rsi.setCurrentRow(newRow);
    
                   BindingContainer bindings1 = BindingContext.getCurrent().getCurrentBindingsEntry();
                   DCIteratorBinding dciter1 = (DCIteratorBinding) bindings1.get("VdetView1Iterator");
                   RowSetIterator rsi1 = dciter1.getRowSetIterator();
                   Row lastRow1 = rsi1.last();
                   int lastRowIndex1 = rsi1.getRangeIndexOf(lastRow1);
                   Row newRow1 = rsi1.createRow();
                   newRow1.setNewRowState(Row.STATUS_NEW);
                   rsi1.insertRowAtRangeIndex(lastRowIndex1 +1, newRow1);
                   rsi1.setCurrentRow(newRow1);
        }
    

    And final saveUpdate method is

        public void saveUpdateButton(ActionEvent actionEvent) {
            // Add event code here...
    
            BindingContainer bindingsBC = BindingContext.getCurrent().getCurrentBindingsEntry();      
    
                   OperationBinding commit = bindingsBC.getOperationBinding("Commit");
                   commit.execute(); 
    
            OperationBinding operationBinding = BindingContext.getCurrent().getCurrentBindingsEntry().getOperationBinding("Commit");
            operationBinding.execute();
            DCIteratorBinding iter = (DCIteratorBinding) BindingContext.getCurrent().getCurrentBindingsEntry().get("VdetView1Iterator");// write iterator name from pageDef.
            iter.getViewObject().executeQuery();  
    
        }
    

    Thanks for all the cooperation to obtain the desired results.

    Concerning

  • If I have the two LOV in the same table then how to connect when I select first and second LOV value also change?

    Mr President

    If I have the two LOV in the same table then how to connect when I select first and second LOV value also change?

    My two fields are FLOW AND DR_NAME

    FLOW = ACCT_ID

    DR_NAME = ACCT_NAME

    I created with success of LOV for these fields.

    First LOV gives acct_id in the debit field and second LOV gives the value of acct_name to dr_name.

    How can I report these lov, it's that when I change my acct_id then acct_name also change

    I have these two tables

    CREATE TABLE "NOM"  (
      "ACCT_ID" VARCHAR2(7) NOT NULL ENABLE, 
      "ACCT_NAME" VARCHAR2(50) NOT NULL ENABLE, 
      "O_BAL" NUMBER(13,2),
      CONSTRAINT NOM_PK PRIMARY KEY ("ACCT_ID")ENABLE
       
       );
    CREATE TABLE "VOUCHERDET" (
      "V_ID" VARCHAR2(9) NOT NULL ENABLE,
      "LINEITEM" NUMBER ,
      "DEBIT" VARCHAR2(7) , 
      "DR_NAME" VARCHAR2(50), 
      "CREDIT" VARCHAR2(7) , 
      "CR_NAME" VARCHAR2(50), 
      "PARTICULARS" VARCHAR2(100), 
      "AMOUNT" NUMBER(21,2),
    CONSTRAINT VOUCHERDET_PK PRIMARY KEY ("V_ID","LINEITEM")ENABLE, 
    CONSTRAINT PUR_SAL_LINE_POD_FK FOREIGN KEY(PROD_ID)
      REFERENCES PRODUCTS (PROD_ID)ENABLE,  
    CONSTRAINT VOUCHERDET_DEBIT_FK FOREIGN KEY ("DEBIT")
       REFERENCES "NOM" ("ACCT_ID") ENABLE, 
    CONSTRAINT VOUCHERDET_CREDIT_FK FOREIGN KEY ("CREDIT")
       REFERENCES "NOM" ("ACCT_ID") ENABLE,  
    CONSTRAINT VOUCHERDET_V_FK FOREIGN KEY ("V_ID")
       REFERENCES "VOUCHER" ("V_ID") ON DELETE CASCADE ENABLE
      );
    
    

    Concerning

    so, instead of this second ActId, choose ACCT_NAME:

  • comparing string values in the same table

    I have a table with ID (14 digit string values) starting with "A". Ex: A21849B1020792. There may be a different ID with the same substring 'B1020792' in the same table, example: A12349B1020792. If this happens, the ID of the last creation date of must be returned in the result. In other words, comparison is done on the same table. "In the example provided, say A12349B1020792 has the date of 1 January 2015 'and A21849B1020792 has date February 1, 2015", since A21849B1020792 has the most recent date, the result must contain only A21849B1020792.

    ID create_date

    ---                              ------------------

    A21849B1020792 02/01/2015

    A12349 B1020792 01/01/2015

    A12345B1234567 01/03/2015      

    A43567B1234567 01/04/2015      


    Here's the query I used:

    substr (a.id, 7) select sc, max (a.create_date) cd1

    of table a, table b

    where a.id! = b.id

    and substr (a.id, 7) = substr (b.id, 7)

    and a.id like 'A %' and b.id like 'A %' / * (I used a % because I am interested only IDs that begin with A) * /.

    and a.id ('A12349B1020792', 'A21849B1020792','A12345B1234567 ','A43567B1234567')

    Group of substr (a.id, 7);

    Result:

    ---------

    sc                    cd1

    ---                    ------

    B1020792 02/01/2015

    B1234567 04/01/2015

    There is one thing that I'm not able to do with my request, that is, be able to get real IDs list and not list of substrings. If I added a.id column in the select clause and the group by clause, the query includes both by substr (a.id, 7) and a.id and as a result, the query returns four lines as below:

    substr (a.id, 7) select sc, max (a.create_date) cd1, a.id ID

    of table a, table b

    where a.id! = b.id

    and substr (a.id, 7) = substr (b.id, 7)

    and a.id like 'A %' and b.id like 'A %' / * (I used a % because I am interested only IDs that begin with A) * /.

    and a.id ('A12349B1020792', 'A21849B1020792','A12345B1234567 ','A43567B1234567')

    Group by substr (a.id, 7), a.id.

    Result:

    ---------

    sc                    cd1                      ID

    ---                    ------                   ---------

    01/01/2015 A12349B1020792 B1020792

    B1020792 01/02/2015 A21849B1020792

    B1234567 01/03/2015 A12345B1234567

    B1234567 01/04/2015 A43567B1234567


    My goal is to retrieve a list of all the unique identifiers that have the later dates.


    ID:

    ---

    A21849B1020792

    A43567B1234567


    Thanks for your time in advance!

    Hello

    user11951344 wrote:

    I have a table with ID (14 digit string values) starting with "A". Ex: A21849B1020792. There may be a different ID with the same substring "B1020792" in the same table, example: A12349B1020792. If this is the case, the ID of the last creation date must be returned in the result. In other words, comparison is done on the same table. "In the example provided, say A12349B1020792 updated 1 January 2015 ' and A21849B1020792 a date February 1, 2015", as A21849B1020792 has the most recent date, the result should contain only the A21849B1020792.

    ID create_date

    ---                              ------------------

    A21849B1020792 02/01/2015

    A12349B1020792 01/01/2015

    A12345B1234567 03/01/2015

    A43567B1234567 01/04/2015

    Here's the query I used:

    substr (a.id, 7) select sc, max (a.create_date) cd1

    of table a, table b

    where a.id! = b.id

    and substr (a.id, 7) = substr (b.id, 7)

    and a.id like 'A %' and b.id like 'A %' / * (I used a % because I am interested only IDs that begin with A) * /.

    and a.id ('A21849B1020792', 'A12345B1234567', 'A12349B1020792', 'A43567B1234567')

    Group of substr (a.id, 7);

    Result:

    ---------

    sc                    cd1

    ---                    ------

    B1020792 02/01/2015

    B1234567 01/04/2015

    There is one thing that I am not able to do with my request, that is, the ability to retrieve the list of IDs real and not a list of substrings. If I added a.id column in the select clause and the group by clause, the query groups according to the two substr (a.id, 7) and a.id and as a result, the query returns four lines as below:

    substr (a.id, 7) select sc, max (a.create_date) cd1, a.id ID

    of table a, table b

    where a.id! = b.id

    and substr (a.id, 7) = substr (b.id, 7)

    and a.id like 'A %' and b.id like 'A %' / * (I used a % because I am interested only IDs that begin with A) * /.

    and a.id ('A21849B1020792', 'A12345B1234567', 'A12349B1020792', 'A43567B1234567')

    Group by substr (a.id, 7), a.id.

    Result:

    ---------

    sc                    cd1                      ID

    ---                    ------                   ---------

    B1020792 01/01/2015 A12349B1020792

    B1020792 02/01/2015 A21849B1020792

    B1234567 03/01/2015 A12345B1234567

    B1234567 01/04/2015 A43567B1234567

    My goal is to retrieve a list of all the unique identifiers that have the later dates.

    ID:

    ---

    A21849B1020792

    A43567B1234567

    Thanks for your time in advance!

    If it makes sense to treat the first 6 characters of the ID separately from the rest of the id in this problem, maybe it makes sense to store those two parts of the id in two different columns.  Relational databases work best when each column of each row contains 1 single piece of data (at most).  It is so fundamental to the design of table that he called the first normal form.

    Given that the two parts are stored in column 1, so you can something like this Request Top - N:

    WITH got_r_num AS

    (

    SELECT r.id

    r.create_date AS cd1

    , RANK () OVER (PARTITION OF SUBSTR (r.id, 7))

    ORDER BY r.create_date DESC

    ) AS r_num

    FROM table_x g - g for data values

    JOIN table_x r - r for related values

    ON SUBSTR (r.id, 7) = SUBSTR (g.id, 7)

    WHERE g.id IN ('A12349B1020792'

    , "A21849B1020792".

    , "A12345B1234567".

    , "A43567B1234567".

    )

    - AND g.id LIKE 'A %' - if necessary.   The above condition ensures already g.id start with "A".

    AND r.id LIKE 'a % '.

    )

    SELECT id, create_date

    OF got_r_num

    WHERE r_num = 1

    ;

    If you would care to post CREATE TABLE and INSERT instructions for the sample data, and then I could test this.

  • Update of several rows of the same table using trigger

    Hello

    I have the following table

    ---------------------------------------------------------------------------------------------------------

    CREATE TABLE ATT_PERMISSIONS
    (
    DATE OF PRMONTHYR,
    EMPIDNUMBER (10)DEFAULT VALUE 0,
    FROMDATETIMEDATE,
    TODMTFDATETIMEDATE,
    NUMBER OF PERMMINS (3),

    SSLINASTRETCH NUMBER (3).

    PERMATTINELIGIBLENUMBER (1)DEFAULT VALUE 0
    );

    ------------------------------------------------------------------------------------------------------

    I want to update the column PERMATTINELIGIBLE in the same table when each line is inserted.

    I created following trigger for that

    CREATE OR REPLACE TRIGGER SSL_AFTER_UPDATE AFTER UPDATE ON ATT_PERMISSIONS

    FOR EACH LINE

    BEGIN

    Update ATT_PERMISSIONS set PERMATTINELIGIBLE =

    (

    SELECT THE CHECK BOX

    WHEN PERMMINS < = 60

    or

    (

    PERMMINS < = SSLINASTRETCH

    AND

    COUNT (CASE WHEN PERMMINS = 0 THEN NULL OTHERWISE 1 END)

    COURSES (PARTITION BY empid, prmonthyr) < = 1

    )

    THEN 1

    0 OTHERWISE

    END

    FROM ATT_PERMISSIONS where prmonthyr =:new.prmonthyr, empid =:new.empid

    ) where prmonthyr =:new.prmonthyr, empid =:new.empid;

    END;

    ---------------------------------------------------------------------------------------------------

    That is to say.

    When a row is inserted the PERMATTINELIGIBLE of all records for this employee for the month is recalculated.

    There would be only two or three records for an employee for a month.

    PERMMINS is the number of minutes to use as short leave.

    If it is less than 60 is eligible for the bonus to attendance for this employee.

    If this isn't normally the date is not eligible for the attendance for this employee premium.

    but an exception is that if a short leaves of DISP employee allowed a month (IE. ( SSLINASTRETCH ) in a straight line, IE. one day, that day is eligible for the bonus of presence.

    That is to say. Why the number of short leaves in a month is taken. If it's one and done minutes use is lower to SSLINASTRETCH, then the day is eligible for the attendance bonus.

    But when I try to create the trigger I get error, PL/SQL: ORA-00907: missing a right parenthesis.

    Help, please

    I use oracle 10g

    I want to update the column PERMATTINELIGIBLE in the same table, when each row is inserted.

    No - you do NOT want to do in a trigger.

    You cannot query the same table that the trigger is activated on. -C' is a MUTANT and you will get an exception.

    When a row is inserted is recalculated to the PERMATTINELIGIBLE of all the records for that employee for that month.

    There would be only two or three records for an employee for a month.

    PERMMINS is the number of minutes to use as short leave.

    If it is less than 60 is eligible for the bonus to attendance for this employee.

    If is not normally the day is not eligible for the premium of attendance for this employee.

    but an exception is that if a short leaves of DISP employee allowed a month (IE. SSLINASTRETCH) in a straight line, IE. one day, that day is eligible for the bonus of presence.

    That is to say. Why the number of short leaves in a month is taken. If it's one and done minutes use is less than SSLINASTRETCH, then the day is eligible for the bonus of presence.

    But when I try to create the trigger I get error, PL/SQL: ORA-00907: missing a right parenthesis.

    You can not do in a trigger. Even if correct you this error of syntax, you will get the exception that I mentioned above.

    Oracle is a multi-user system. Other users can modify the same table that you use.

    So even if you could try to interview "all the records for this employee" some of them may be locked if other users access them. Also, an insert statement could try to insert two rows for an employee and the trigger could not have seen the other lines still.

    If you want to work with data SETS (all records for an employee), you must write the PL/SQL code that LOCKS all lines updated to prevent others to interfere.

    Then you make your operations but NOT in a trigger. Perform inserts and then use an UPDATE query to set this value.

    Then VALIDATE to unlock the lines.

  • Update lines with the info from the other rows in the same Table.

    I'm trying to update the lines with the information of the same table. The table is loaded with information from a report that runs and there must be a new entry every month, but I would like to bring some of the info from the last month. This statement below works but updates all rows in the new load table and in my test case, I only did a few game only like 5 files need to get updates. It is an example of what I'm trying to do. If I add this (C2. COL_INVC_ID = C1. COL_INVC_ID) until the last "* where *" statement get an invalid identifier for 'C2 '. COL_INVC_ID ". So what I'm doing wrong here? How can I update only the lines where also in recent months run?

    Thanks in advance for any help!

    ------------
    Update OpenIssues OI1
    Together (OI1. NUM, OI1. Status, OI1. Code, OI1. LastModifiedDate) =
    (Select ios2. NUM, ios2. Status, ios2. Code, ios2. LastModifiedDate
    Of OpenIssues ios2
    Where OI2.num = OI1.num and ios2. TableLoadDate = TO_DATE (January 31, 2012 00:00:00 ',' ' the HH24: MI: SS DD/MM/YYYY)
    )
    Where and OI1. TableLoadDate = TO_DATE (February 29, 2012 00:00:00 ',' ' the HH24: MI: SS DD/MM/YYYY)
    ------------


    SQLMe

    As Frank suggested merger is much effective here, go...

      create table  temp
    as(
    select 1 eno, 1 amt , sysdate load_date from dual union all
    select 1 eno, 2 amt , add_months(sysdate,1) load_date from dual union all
    select 2 eno, 1 amt , sysdate load_date from dual union all
    select 2 eno, 2 amt , add_months(sysdate,1) load_date from dual
    );
    
    merge into temp t
    using (select eno, amt, load_date
             from temp
            where trunc(Load_Date) = TO_DATE('05/30/2012', 'MM/DD/YYYY')) s
    on ((s.eno = t.eno) and trunc(t.Load_Date) = TO_DATE('06/30/2012', 'MM/DD/YYYY'))
    when matched then
      update set t.amt = s.amt;
    commit;
    
    select * from temp;
    
  • FRM - 40202:Field must be entered on two blocks with the same table

    I have two blocks, blockA and blockB, both from the same table that is tableX.

    When I ask of blockA and it worked, then I go to blockB and modify data, and save, there is no problem. But when I do not run the query of blockA or if the query did not return any results, I go to blockB and change some data then save, I got this error. The cursor then go to first blockA point. So now, I have to delete this empty line before the Save.


    Any suggestion?

    you set a few initial values programmatically for a block?
    in this case, the status changes to INSERT and you will get this message.
    You can check the staus with GET_RECORD_PROPERTY (1, "A BLOCK", STATUS), e.g. with the trigger KEY-COMMIT.

  • Copy the data rows in the same table

    Here is the structure of the table, I work I would like all the value with ID = 1 in new lines. The ID must be 2 with the same data.

    I am using following query to accomplish, but get the error.

    Insert into hsp_column_detail_item (DETAIL_ID, VALUE, POSITION, GENERATION, OPERATOR, LABEL)

    Select 2, POSITION, GENERATION, OPERATOR, VALUE, LABEL

    Of

    hsp_column_detail_item

    where

    detail_id = 1

    ORA-02291: integrity constraint (PLANSAMP. FK_HSP_DETAIL_ID) violated - key parent not found

    Columns

    Detail_ID1THEREINTEGER NUMBERFrequency
    VALUE2THEREFLOATNone
    POSITION3THEREINTEGER NUMBERNone
    GENERATION4THEREINTEGER NUMBERNone
    OPERATOR5THEREINTEGER NUMBERNone
    LABEL6THEREVARCHAR2 (1500 bytes)None

    Sample data:

    Label Detail_ID value generation operator Position

    1500001ABC

    1300101def

    1200201EFG

    Index

    Name of the indexColumn name

    Col_Detail_ItemDetail_ID

    Col_Detail_ItemPosition

    866532 wrote:

    Where detail_id in

    (select detail_id in the hsp_column_detail where)

    dim1 = (select object_id from hsp_object where the object_name = 'Real' and object_type = 31) and

    Dim5 = (select object_id from hsp_object where the object_name = 'Work' and object_type = 35) and

    dim7 = (select object_id from hsp_object where the object_name = 'FY13' and object_type = 38)

    );

    ORA-00001: unique constraint (PLANSAMP. Voilated PK_HSP_COL_DETAIL)

    To not violate the unique constraint, two requirements:

    -The detail_id 5 you insert would not already exist in the table

    -Since you are forcing this detail_id, your subquery must return only one row: so you can write ' detail where id = (select...) "and:

    -either the dim1 / dim5 / dim7 filters are quite selective

    - or to make any decision on which detail_id to reproduce: max (detail_id) or min (detail_id) or any other way yo select the right / arbitrary

  • Need a script to select the update the row to another row in the same table

    I have a table with the columns and values
    KeyID       EffectiveDate     InactiveDate
    1              01/01/2013
    1              01/02/2013
    1              01/03/2013
    2              12/31/2012
    2              01/02/2013
    2              01/03/2013
    I need to update the InactiveDate of a line with the EffectiveDate of a line with the EffectiveDate newer than the update line and the even KeyID.
    KeyID       EffectiveDate     InactiveDate
    1              01/01/2013      01/02/2013
    1              01/02/2013      01/03/2013
    1              01/03/2013
    2              12/31/2012      01/02/2013
    2              01/02/2013      01/03/2013
    2              01/03/2013
    I want to have a select script that shows
    KeyID       EffectiveDate        InactiveDate    New_InactiveDate
    1              01/01/2013                              01/02/2013
    1              01/02/2013                              01/03/2013
    1              01/03/2013
    2              12/31/2012                              01/02/2013
    2              01/02/2013                              01/03/2013
    2              01/03/2013
    Thanks for any help.

    Published by: 881656 on January 3, 2013 17:57

    Published by: 881656 on January 3, 2013 18:15

    Published by: 881656 on January 3, 2013 18:20

    Hello

    881656 wrote:
    I have a table with the columns and values

    KeyID       EffectiveDate     InactiveDate
    1              01/01/2013
    1              01/02/2013
    1              01/03/2013
    2              12/31/2012
    2              01/02/2013
    2              01/03/2013
    
    I need to update the InactiveDate of a row with the EffectiveDate of a row with the newer EffectiveDate than the row to be updated and with the same KeyID.
    
    KeyID       EffectiveDate     InactiveDate
    1              01/01/2013      01/02/2013
    1              01/02/2013      01/03/2013
    1              01/03/2013
    2              12/31/2012      01/02/2013
    2              01/02/2013      01/03/2013
    2              01/03/2013
    

    This sounds like a job for the analytical function of LEAD:

    MERGE INTO table_x     dst
    USING (
         SELECT  keyid
         ,     effectivedate
         ,     LEAD (effectivedate) OVER ( PARTITION BY  keyid
                                           ORDER BY         activedate
                                         )            AS inactivedate
          )               src
    WHEN MATCHED THEN UPDATE
    ON    (    src.id          = dst.id
          AND  src.effectivedate     = dst.effectivedate
          )
    SET     dst.inactivedate     = src.inactivedate
    ;
    
    I want to have a select script which shows
    
    KeyID       EffectiveDate        InactiveDate    New_InactiveDate
    1              01/01/2013                              01/02/2013
    1              01/02/2013                              01/03/2013
    1              01/03/2013
    2              12/31/2012                              01/02/2013
    2              01/02/2013                              01/03/2013
    2              01/03/2013
    

    Once that you have done the above MERGER, it is simply:

    SELECT    *
    FROM      table_x
    ORDER BY  keyid
    ,         effectivedate
    ;
    

    If you do not have sthe FUSION, then see the query in the USING clause of the MERGER.

    I hope that answers your question.
    If not, post a small example data (CREATE TABLE and only relevant columns, INSERT statements), and the results you want from this data.
    In the case of a DML (UPDATE), for example, the sample data should show what looks like the tables before the DML, and the results will be the content of the table changed after the DML.
    Explain, using specific examples, how you get these results from these data.
    Always say what version of Oracle you are using (for example, 11.2.0.2.0).
    See the FAQ forum {message identifier: = 9360002}

  • Compare several records in the same table

    Hello, I m writing a bat file so I can export information that I question.

    I have an automatic integration which checks from time to time if there is no new client´s and generates a trigger.
    If an error levonorgestrol I the process is repeated until the client is located in the database.
    I can't create tables or change the structure.


    My problem is that I need to compare the record more updated with the CLIENT_ID field
    Let me give you an example:


    Table A

    ERROR_MESSAGE CREATEDUSERID CLIENT_ID
    0 success 01/01/2009
    1 error 01/01/2009
    2 success 01/01/2009
    1 success 01/02/2009
    3 success 01/02/2009
    4 error 01/02/2009

    I need to compare "1" client created on 01/01/2009 this error gived with new records to see if there's success and my
    query should only return the client_ID '4' and export with sqlplus

    Could you please help me?

    Hello

    It works very well with my data.
    What data do you use? After a few lines of sample data (CREATE TABLE AS executable... or INSERT... statements are best) that give you wrong results.

    Make sure that everything is spelled correctly.
    For example, roughly halfway through the query, you say

    and io.status = 'Erro' 
    

    and at the end you say

    having max(decode(io.status, 'Error', 1, 2))  ...
    

    That is the same ("Error" or "Error") in both places?

  • subtracting the two rows in the same column

    Hello
    I have the following table with about 6000 lines of different year_month, but I compare and subtract v
    Contribution of the Organization Year_month
    Kano 200000 JAN-2011
    KADUNA 300000 JAN-2011
    ABUJA 400000 JAN-2011
    Kano 300000 FEB-2011
    KADUNA 200000 FEB-2011
    ABUJA 600000 FEB 2012
    I want to choose a year_month runtime to subtract the contribution of the first contribution of the second year_month year_month and give me the result, as shown in the following table
    Difference of JAN - FEB 2011 - 2011 organization
    Kano 200000 300000-100000
    300000 200000 100000 KADUNA
    ABUJA 400000 200000 600000
    Here is my code back will too

    create or replace function "GET_MONTHLY_VALUE".
    (q_name in VARCHAR2,
    hmoCode in VARCHAR2)
    return VARCHAR2
    is
    number of C1;
    Start
    Select NHIS_CONTRIBUTION in c1 of CONTRIBUTION_MGT where upper (YEAR_MONTH) = upper (q_name) and upper (ORGANIZATION) = upper (hmoCode);

    return to c1;
    exception when NO_DATA_FOUND THEN
    Returns a null value.
    end;

    -a call to the function above:

    create or replace function process_cont_monthly return varchar

    is
    Cursor cont_cursor is select ORGANIZATION of CONTRIBUTION_MGT;
    Start
    for
    cont_rec loop cont_cursor
    First, select GET_MONTHLY_VALUE(:p26_month,cont_rec.ORGANIZATION) GET_MONTHLY_VALUE(:p26_month2,cont_rec.ORGANIZATION) second,
    ABS (GET_MONTHLY_VALUE (:p26_month,cont_rec.ORGANIZATION)-GET_MONTHLY_VALUE(:p26_month2,cont_rec.ORGANIZATION)) difference
    of CONTRIBUTION_MGT;

    end loop;
    commit;
    end;
    I got totally confused and do not know what to do next
    Any help and the best guide is appreciated

    Analytics can also be used (assuming that you store dates as dates, ORDER BY working properly)

    create table t(org varchar2(10),mon date, cont number);
    insert into t(org,mon,cont) values ('Kano',to_date('201101','YYYYMM'),200000);
    insert into t(org,mon,cont) values ('KADUNA',to_date('201101','YYYYMM'),300000);
    insert into t(org,mon,cont) values ('Kano',to_date('201102','YYYYMM'),300000);
    insert into t(org,mon,cont) values ('KADUNA',to_date('201102','YYYYMM'),200000);
    commit;
    
    select * from t;
    ORG        MON                    CONT
    ---------- ---------------------- ----
    Kano       01-JAN-2011 00:00:00   200000
    KADUNA     01-JAN-2011 00:00:00   300000
    Kano       01-FEB-2011 00:00:00   300000
    KADUNA     01-FEB-2011 00:00:00   200000 
    
    select org,cont1 start_month,cont2 end_month,cont1-cont2 difference
      from (
            select org,mon,cont cont1,
                   lead(cont) over (partition by org order by mon) as cont2
            from t
            where  mon in (to_date('201101','YYYYMM'),to_date('201102','YYYYMM'))
            )
    where cont2 is not null;
    
    ORG        START_MONTH END_MONTH DIFFERENCE
    ---------- ----------- --------- ----------
    KADUNA          300000    200000     100000
    Kano            200000    300000    -100000 
    
  • ViewCriteria comparing two columns of the table to create

    Anyone know how I can create a ViewCriteria where clause that compares the two columns of the same table?

    For example if I had two columns of integers (MINSAL and MAXSAL) and wanted to see if they are equal. Normally, I would do the following SQL below.

    SELECT * EMPL
    WHERE MINSAL = MAXSAL

    Try to link any of them to an expression of groovy.

    Timo

  • How to update columns with the value of other lines in the same table

    Hello

    I use Oracle 11.2, I'd use SQL statements to update a column based on values in other rows in the same table. Here are the details:

    create table TB_test (number 4 myId, crtTs date, date of MDPU);

    insert into tb_test (1, to_date ('20110101', 'YYYYMMDD'), null);
    insert into tb_test (1, to_date ('20110201', 'YYYYMMDD'), null);
    insert into tb_test (1, to_date ('20110301', 'YYYYMMDD'), null);
    insert into tb_test (2, to_date ('20110901', 'YYYYMMDD'), null);
    insert into tb_test (2, to_date ('20110902', 'YYYYMMDD'), null);

    After you run the SQL code, I would like to have the following result:

    1, 20110101, 20110201
    1, 20110201, 20110301
    1, 20110301, null
    2, 20110901, 20110902
    2, 20110902, null

    Thanks for your suggestion.

    I guess you need this, otherwise please explain logic correctly:

    SQL> merge into tb_test t
      2  using (
      3    select rowid as rid
      4         , lead(crtts) over(partition by myid order by crtts) as updts
      5    from tb_test
      6  ) v
      7  on (t.rowid = v.rid)
      8  when matched then update
      9   set t.updts = v.updts
     10  ;
    
    5 rows merged.
    
    SQL> select * from tb_test order by 1,2;
    
          MYID CRTTS     UPDTS
    ---------- --------- ---------
             1 01-JAN-11 01-FEB-11
             1 01-FEB-11 01-MAR-11
             1 01-MAR-11
             2 01-SEP-11 02-SEP-11
             2 02-SEP-11
    
  • Comparing the same tables of two schemas

    I had already posted a similair on this thread. So, I thought I would start a new thread on this to avoid confusion

    I want to generate a report that shows the difference in the data type of the columns in the same table in two different patterns.

    The query using LESS shows the difference below.

    create table SCOTT.mytab1 (empid number);
    create table HR.mytab1 (empid varchar2(34));
    
    
    SELECT   table_name, column_name, OWNER schema, data_type
    FROM     dba_tab_cols where owner = 'SCOTT'
    AND TABLE_NAME = 'MYTAB1'
    MINUS
    SELECT   table_name, column_name, OWNER schema, data_type
    FROM     dba_tab_cols where owner = 'HR'
    AND TABLE_NAME = 'MYTAB1'
    
    Result:
    TABLE_NAME      COLUMN_NAME     SCHEMA     DATA_TYPE
    --------------- --------------- ---------- ------------
    MYTAB1          EMPID           SCOTT      NUMBER
    But, since it is a report, I want to see the form of results the two schemas that has column of different data types with the same names of table

    Expected results:
    TABLE_NAME      COLUMN_NAME     SCHEMA     DATA_TYPE
    --------------- --------------- ---------- ------------
    MYTAB1          EMPID           SCOTT      NUMBER
    MYTAB1          EMPID           HR         VARCHAR2
    Anyway I could do this?

    Why not get a single line with two types of data:

    select a.table_name, a.column_name, a.data_type schema1_type, b.data_type schema2_type
    from all_tab_columns a, all_tab_columns b
    where a.owner = 'SCOTT'
    and b.owner = 'HR'
    and a.table_name=b.table_name
    and a.column_name=b.column_name
    and a.data_type!=b.data_type;
    

    This extracted single query columns present on the two schemas but with different data types. These columns only on one of the two schemas are not extracted.

    Max

Maybe you are looking for

  • should iPad Air (1) - I upgrade to IOS 10?

    Hi all I have an iPad Air (1 no air no 2)-should I upgrade to IOS 10? I wonder about SPEED problems - it will run a slower - or more fast - or about the same speed as IOS9?

  • Dismantled Journe scan - need help

    I disassembled my Journe scanner to attempt to clean the roller but can't put it back together again! It has two springs that I can't work where they are going. Can I pay Toshiba to clean and re - assemble for me?

  • RT or-9148 how to build a distributed measurement system

    Hello! I just intend to build such a system, based on the cRIO 9014 and 9148. My problem is that I don't know how to link these two devices by Ethernet. Cannot add the Chassis 9148 to cRIO9014 (it may have a single chassis). All modules IO 9148 Chass

  • correct settings for two networks?

    I have a desk that has a building at each end of the city.  I have a wireless bridge that connects the buildings.  Each building is on its own ip configuration and has its own internet connection.  I have a server for A construction program.  I want

  • Wireless on HP Deskjet 3050 a - J611 radio

    Hello world! I had my HP Deskjet 3050 a - J611 wireless printer set up sometimes too before on two different networks. But I have moved and deed of sale to set up again... Initially through the push button method he was always trying to connect to my