Date history table

I'm struggling with a basic query in Oracle and I'm having some trouble getting my head around it. Basically, the table is like this:
ID STATUS_DATE CLIENT_STATUS
1 12/10/2010 P
1 12/09/2010 C
1 12/03/2010 D
2 11/15/2010 E
2 11/16/2010 F
I want the query to return the max date and the most recent date group by ID. So the result should be for ID = 1 followed by 2.
ID CURRENT STATUS DATE PREVIOUS_STATUS_DATE CURRENT_STATUS PREVIOUS_STATUS
1 12/10/2010 12/09/2010 P C
2 11/16/2010 11/15/2010 F E
Basically, the query involves selecting Status_DATE Current_STATUS_DATE
ORDER BY STATUS_DATE
GROUP BY ID
--where each GROUP ID = 2
To clarify - I want the Max date of the Client ID group followed by the next date in order - only two rows but I want the results in one row.
The problem where I'm stumped over is trying to obtain the previous status and the previous status date..
Happy New Year!

Hi,
Welcome to the forum!
Use the analytic ROW_NUMBER function to number the rows of each id in descending order by status_date:
WITH     got_r_num     AS
     SELECT     id, status_date, client_status
     ,     ROW_NUMBER () OVER ( PARTITION BY  id
                         ORDER BY        status_date     DESC
                       )     AS r_num
     FROM     table_x
--     WHERE     ...     -- Any filtering goes here
SELECT       id
,       MIN (CASE WHEN r_num = 1 THEN status_date   END)     AS current_status_date
,       MIN (CASE WHEN r_num = 2 THEN status_date   END)     AS previous_status_date
,       MIN (CASE WHEN r_num = 1 THEN client_status END)     AS current_status
,       MIN (CASE WHEN r_num = 2 THEN client_status END)     AS previous_status
FROM       got_r_num
GROUP BY  id
;The main query is an example of a Pivot , where you display a column from multiple rows as multiple columns on one row. There's a better way to do it in Oracle 11, but you didn't say what version of Oracle you're using. As written, the query above will work in Oracle 9 (and up), and can be easily modified to run in Oracle 8.1.

Similar Messages

  • Moving Data from Normal table to History tables

    Hi All,
    I'm in the process of moving data from normal tables to
    History tables.
    It can be some sort of a procedure which should be a cron job running at night.
    My aim is to move data say 1.5 yrs or 2yrs old data to History tables.
    What aspects i need to check when moving data. And how can i write a procedure for this requirement.
    The schema is same in both the normal table and history table.
    It has to be a procedure based on particular field RCRE_DT.
    If the rcre_dt is above 2 yrs the data needs to be moved to HIS_<table>.
    I have to insert record in to HIS_table and simultaneously delete record from the normal table.
    This is in Production system and the tables are quite big.
    Pls do find enclosed the attached sample schema for Normal table and HIS_<table>.
    If i want to automate this script as a Cron job for similarly other History tables
    how am i to do it in a single procedure assuming the procedure for moving the data is the same procedure.
    Thanks for ur help in advance.
    SQL> DESC PXM_FLT;
    Name Null? Type
    RCRE_USER_ID NOT NULL VARCHAR2(15)
    RCRE_DT NOT NULL DATE
    LCHG_USER_ID VARCHAR2(15)
    LCHG_DT DATE
    AIRLINE_CD NOT NULL VARCHAR2(5)
    REF_ID NOT NULL VARCHAR2(12)
    BATCH_DT NOT NULL DATE
    CPY_NO NOT NULL NUMBER(2)
    ACCRUAL_STATUS NOT NULL VARCHAR2(1)
    FLT_DT NOT NULL DATE
    OPERATING_CARRIER_CD NOT NULL VARCHAR2(3)
    OPERATING_FLT_NO NOT NULL NUMBER(4)
    MKTING_CARRIER_CD VARCHAR2(3)
    MKTING_FLT_NO NUMBER(4)
    BOARD_PT NOT NULL VARCHAR2(5)
    OFF_PT NOT NULL VARCHAR2(5)
    AIR_CD_SHARE_IND VARCHAR2(1)
    UPLOAD_ERR_CD VARCHAR2(5)
    MID_PT1 VARCHAR2(5)
    MID_PT2 VARCHAR2(5)
    MID_PT3 VARCHAR2(5)
    MID_PT4 VARCHAR2(5)
    MID_PT5 VARCHAR2(5)
    PAX_TYPE VARCHAR2(3)
    PAY_PRINCIPLE VARCHAR2(1)
    SQL> DESC HIS_PXM_FLT;
    Name Null? Type
    RCRE_USER_ID NOT NULL VARCHAR2(15)
    RCRE_DT NOT NULL DATE
    LCHG_USER_ID VARCHAR2(15)
    LCHG_DT DATE
    AIRLINE_CD NOT NULL VARCHAR2(5)
    REF_ID NOT NULL VARCHAR2(12)
    BATCH_DT NOT NULL DATE
    CPY_NO NOT NULL NUMBER(2)
    ACCRUAL_STATUS NOT NULL VARCHAR2(1)
    FLT_DT NOT NULL DATE
    OPERATING_CARRIER_CD NOT NULL VARCHAR2(3)
    OPERATING_FLT_NO NOT NULL NUMBER(4)
    MKTING_CARRIER_CD VARCHAR2(3)
    MKTING_FLT_NO NUMBER(4)
    BOARD_PT NOT NULL VARCHAR2(5)
    OFF_PT NOT NULL VARCHAR2(5)
    AIR_CD_SHARE_IND VARCHAR2(1)
    UPLOAD_ERR_CD VARCHAR2(5)
    MID_PT1 VARCHAR2(5)
    MID_PT2 VARCHAR2(5)
    MID_PT3 VARCHAR2(5)
    MID_PT4 VARCHAR2(5)
    MID_PT5 VARCHAR2(5)
    PAX_TYPE VARCHAR2(3)
    PAY_PRINCIPLE VARCHAR2(1)

    Hi All,
    Thanks for ur valuable suggestion.But can u explain me bit more on this as i'm still confused about switching between partitoned tables and temporary table.Suppose if i have a table called PXM_FLT and an correspoding similar table named HIS_PXM_FLT.How can i do the partitioning shd i do the partitioning on the normal table or HIS_PXM_FLT.i do have a date field for me to partition based on range.Can u pls explain why shd i again create a temp.table.What's the purpose.Now the application is designed in such a way that old records have to be moved to HIS_PXM_FLT.can u pls highlight more on this.Your suggestions are greatly appreciated.As i'm relatively new to this partitioning technique i'm bit confused on how it works.But i came to understand Partitioning is a better operation than the normal insert or delte as it is more data intensive as millions of record need to be moved.Thanks for feedback and ur precious time.

  • DB Adapter inserting data in to regular tables and LOG / History tables

    I have a requirement of reading a XML file using the File Adapter and inserting into Data base.
    I'm using File Adapter --> Mediator --> DB Adapter
    When I insert the data I have to insert in to regular tables and LOG / History tables the same data.
    There is a foreign key relationship with regular table and History table. How to insert in to both tables (regular and LOG / History)?
    Thanks in advance

    while configuring the adapter, you need to create the relationships between the two tables, while importing the tables, import the two tables...
    http://docs.oracle.com/cd/E23943_01/integration.1111/e10231/adptr_db.htm#BDCGCCJB
    go to 9.2.7 Creating Relationships.
    HTH
    N

  • How to save history change data on table

    Hi all
    I'm using Oracle Database 11g
    Data of tables often is changed. I want to save history person changed it.
    Anybody help me!
    Thankyou
    Thiensu2810

    Hi
    you can use
    flashback data archieve
    CREATE FLASHBACK ARCHIVE DEFAULT test_archive1
    TABLESPACE example
    QUOTA 1 M
    RETENTION 1 DAY;
    CREATE FLASHBACK ARCHIVE test_archive2
    TABLESPACE example
    QUOTA 1 M
    RETENTION 1 DAY;
    The next statement alters the default flashback data archive to extend the retention period to 1 month:
    ALTER FLASHBACK ARCHIVE test_archive1
    MODIFY RETENTION 1 MONTH;
    The next statement specifies tracking for the oe.customers table. The flashback data archive is not specified, so data will be archived in the default flashback data archive, test_archive1:
    ALTER TABLE oe.customers
    FLASHBACK ARCHIVE;
    The next statement specifies tracking for the oe.orders table. In this case, data will be archived in the specified flashback data archive, test_archive2:
    ALTER TABLE oe.orders
    FLASHBACK ARCHIVE test_archive2;
    The next statement drops test_archive2 flashback data archive:
    http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/statements_5009.htm#SQLRF20008
    hope this helps
    Zekeriya

  • Query for Finding the Date History

    Hi Geeks,
    My Table looks like this
    Employee Assignment Position     Job     Grade     Start_date     End_date
    101 132 2055 Clerk C01 10-Mar-00 11-Feb-01
    101 132 2055 Clerk C02 12-Feb-01 15-Dec-01
    101 132 2056 Clerk C02 16-Dec-01 22-Jul-03
    101 132 2055 Clerk C03 23-Jul-03 31-Dec-4000 --(unassigned)
    Now I need output like
    Employee Assignment Position Start_date End_date
    101 132 2055 10-Mar-2000 15-Dec-2001
    101 132 2056 16-Dec-2001 22-Jul-2003
    101 132 2055 23-Jul-2003 31-Dec-4000 --(unassigned)
    The following important things are to be considered
    1. Rows to be grouped by position
    2. Each row much have the start date and end date of the employee position. If the employee is the same postion and different grade or job that doesnt matter. But if the employee jumps from his position (2055) to 2056 and after sometime he comes to the same position (i.e. 2055) the date history should be separate.
    I am unable to derive the logic also. I think we need to create a function for this.
    Kindly help me out.
    Thanks in Advance
    Punithavel
    Message was edited by:
    Punithavel
    Message was edited by:
    Punithavel

    Too difficult to read. I have no database access to test (usually I use a step by step approach, proceeding with the next step when the current one is OK).
    I can describe a general idea (may post something afterwards with no promise it will work)
    step 1: mark the position changes
    step 2: retain only mark 1 and mark max(mark) of each group
    step 3: make a single row from the two rows of each group
    Regards
    Etbin
    with
    marking as
    (select employee,assignment,position,start_date,end_date,
            row_number() over (partition by employee,assignment,position order by start_date) the_mark
       from the_table
    collecting as
    (select employee,assignment,position,start_date,end_date,the_mark
       from marking m
      where the_mark = 1
         or the_mark = (select max(the_mark)
                          from marking
                         where employee = m.employee
                           and assignment = m.assignment
                           and position = m.position
                         group by employee,assignment,position
                         having count(*) > 1
    combining as
    (select employee,assignment,position,
            case when the_mark = 1 then start_date end start_date,
            case when the_mark = 1
                 then case when lead(position,1) over (partition by employee,assignment,position order by start_date) = position
                           then lead(end_date,1) over (partition by employee,assignment,position order by start_date)
                           else end_date
                      end
            end end_date
       from collecting
    select employee,assignment,position,start_date,end_date
      from combining
    where start_date is not null
    order by employee,assignment,position,start_date*** not tested ***
    Message was edited by: Etbin
    user596003
    on a lazy afternoon I took a look at your friend's solution too and I like it.
    It's more concise than mine (defining starts and ends).
    Not being able to test it the only problem in his solution might be the absence of order by clauses to assign correct rownums
    WITH lag_and_lead AS
    (SELECT employee,assignment,position,start_date,end_date,
            LAG (position) OVER (PARTITION BY employee,assignment ORDER BY start_date) AS lag_position,
            LEAD (position) OVER (PARTITION BY employee,assignment ORDER BY start_date) AS lead_position
       FROM your_table
      ORDER BY employee,assignment,start_date
    starts AS
    (SELECT employee,assignment,position,start_date,ROWNUM rn
       FROM lag_and_lead
      WHERE position <> lag_position
         OR lag_position IS NULL
      order by employee,assignment,start_date
    ends AS
    (SELECT employee,assignment,position,end_date,ROWNUM rn
       FROM lag_and_lead
      WHERE position <> lead_position
         OR lead_position IS NULL
      order by employee,assignment,start_date
    SELECT starts.employee,starts.assignment,starts.position,starts.start_date,ends.end_date
      FROM starts,ends
    WHERE starts.employee = ends.employee
       AND starts.assignment = ends.assignment
       AND starts.position = ends.position
       AND starts.rn = ends.rn
    EMPLOYEE ASSIGNMENT POSITION JOB   GRADE START_DATE  END_DATE
         101        132     2055 Clerk C01   10-Mar-2000 11-Feb-2001
         101        132     2055 Clerk C02   12-Feb-2001 15-Dec-2001
         101        132     2056 Clerk C02   16-Dec-2001 22-Jul-2003
         101        132     2055 Clerk C03   23-Jul-2003 31-Dec-4000
    lag_and_lead
    EMPLOYEE ASSIGNMENT POSITION START_DATE  END_DATE    lag_position lead_position
         101        132     2055 10-Mar-2000 11-Feb-2001         null          2055
         101        132     2055 12-Feb-2001 15-Dec-2001         2055          2056
         101        132     2056 16-Dec-2001 22-Jul-2003         2055          2055
         101        132     2055 23-Jul-2003 31-Dec-4000         2056          null
    starts
    EMPLOYEE ASSIGNMENT POSITION START_DATE  rn
         101        132     2055 10-Mar-2000  1
         101        132     2056 16-Dec-2001  2
         101        132     2055 23-Jul-2003  3
    ends
    EMPLOYEE ASSIGNMENT POSITION END_DATE    rn
         101        132     2055 15-Dec-2001  1
         101        132     2056 22-Jul-2003  2
         101        132     2055 31-Dec-4000  3
    EMPLOYEE ASSIGNMENT POSITION START_DATE  END_DATE
         101        132     2055 10-Mar-2000 15-Dec-2001
         101        132     2056 16-Dec-2001 22-Jul-2003
         101        132     2055 23-Jul-2003 31-Dec-4000Regards
    Etbin
    Message was edited by: Etbin
    user596003

  • AR DATA FLOW (TABLE LEVEL) - ON ACCOUNT CREDITS & CASH RECEIPTS편

    제품 : FIN_AR
    작성날짜 : 2003-09-16
    AR DATA FLOW (TABLE LEVEL) - ON ACCOUNT CREDITS & CASH RECEIPTS편
    ================================================================
    PURPOSE
    이 문서에서는 AR table들에 대해 어떻게 data가 들어가는지에 대해
    설명한다.
    On Account와 Cash Receipt을 기준으로 설명한다.
    Explanation
    1. On Account Credits
    특정 Customer에 대한 Credit정보를 입력했으나, 아직 특정 Invoice에는 Apply되지 않은 정보를 "On Account" credit이라고 한다.
    Credit정보가 들어있기 때문에, Credit Memo와 유사하게 table에 저장된다.
    Credit Memo와 다른 점은 아래와 같다.
    o When first entered the payment schedule will be fully remaining.
    o When first entered no records are inserted into AR_RECEIVABLE_APPLI
    CATIONS_ALL.
    o The line records will have NULL values in
    PREVIOUS_CUSTOMER_TRX_ID
    PREVIOUS_CUSTOMER_TRX_LINE_ID
    o The distribution lines have to be typed in as there is no invoice
    to copy them from.
    "On Account"는 같은 Supplier상에서는 어떠한 invoice에 대해서 적용이 가능하다는 점에서,
    특정 invoice에만 apply가 가능한 Credit Memo와는 다르다.
    2. Cash Receipts
    Recipt정보가 입력되면, 아래의 table들에 insert된다.
    o AR_CASH_RECEIPTS_ALL
    o AR_CASH_RECEIPT_HISTORY_ALL
    o AR_PAYMENT_SCHEDULES_ALL
    o AR_RECEIVABLE_APPLICATIONS_ALL
    입력된 Receipt정보가 특정 invoice와 match되면, 추가 record가
    AR_RECEIVABLE_APPLICATIONS_ALL에 insert되고, AR_PAYMENT_SCHEDULE_ALL에는 update된다.
    | | | |
    | RECEIPT |------------------| PAYMENT |
    | | | SCHEDULE |
    | |
    | |
    ^ ^
    /|\ /|\
    | | | |
    | RECEIPT | |APPLICATIONS|
    | HISTORY | | |
    2.1 AR_CASH_RECEIPTS_ALL
    Receipt에 대한 기본정보가 insert된다. 한 receipt당 한줄이 insert된다.
    Key = CASH_RECEIPT_ID (from sequence AR_CASH_RECEIPTS_S)
    Important Fields
    AMOUNT - Value of receipt in entered currency
    RECEIPT_NUMBER - Payment Number entered by user.
    STATUS - (APP)lied, (UNAPP)lied, (REV)ersed Payment,
    (STOP) payment, (NSF) insufficient funds.
    It will only change to APP once the whole
    amount of the receipt is applied.
    REVERSAL_DATE - NULL unless receipt reversed
    PAY_FROM_CUSTOMER - Contains CUSTOMER_ID for RA_CUSTOMERS
    2.2 AR_CASH_RECEIPT_HISTORY_ALL
    Receipt하나당 한줄의 data가 insert되고, GL로 Posting된 정보가 들어간다.
    Receipt이 reverse되면, 새로운 row가 insert된다.
    Key = CASH_RECEIPT_HISTORY_ID (from sequence)
    Important Fields
    CASH_RECEIPT_ID - Foreign key to AR_CASH_RECEIPTS record.
    STATUS - CLEARED for manually input receipts.
    GL_DATE - Accounting date
    ACCOUNT_CODE_COMBINATION_ID - Key to GL_CODE_COMBINATIONS
    POSTING_CONTROL_ID - -3 if unposted
    REVERSAL_POSTING_CONTROL_ID - NULL unless payment reversed
    CURRENT_RECORD_FLAG - Y if this is latest record
    PRV_STAT_CASH_RECEIPT_HIST_ID - Key to previous receipt history record.
    2.3 AR_PAYMENT_SCHEDULES_ALL
    Invoice에 apply된 Total 금액정보가 저장된다.
    Key = PAYMENT_SCHEDULE_ID (from sequence)
    Important Fields
    CUSTOMER_TRX_ID - NULL
    CASH_RECEIPT_ID - Foreign key to AR_CASH_RECEIPTS record.
    AMOUNT_DUE_ORIGINAL - Total amount of receipt (usually negative)
    AMOUNT_DUE_REMAINING - Unapplied amount of receipt.
    AMOUNT_APPLIED - How much of this receipt is applied .
    STATUS - (OP)en or (CL)osed. Will only be closed if
    AMOUNT_DUE_REMAINING is zero.
    All of the fields holding LINE, TAX and FREIGHT amounts are NULL.
    2.4 AR_RECEIVABLE_APPLICATIONS
    Receipt이 처음 생성될때, 한줄의 data가 이 table에 insert되고,
    invoice에 대해 Apply혹은 Unapply가발생하면, 두줄씩 새롭게 생성된다.
    예를들면, 아래와 같다.
    Record 1 UNAPP 700
    { Record 2      UNAPP       -200
    { Record 3      APP          200      cross referenced to the Invoice
    { Record 4      UNAPP       -500
    { Record 5      APP          500      cross referenced to 2nd Invoice
    The sum of the amounts on records that have a particuar status should add up
    to the running totals on the payment schedulesi, but with the opposite sign.
    i.e. In the example above
    AR_PAYMENT_SCHEDULES.AMOUNT_DUE_ORIGINAL = -700
    AR_PAYMENT_SCHEDULES.AMOUNT_DUE_REMAINING = 0
    AR_PAYMENT_SCHEDULES.AMOUNT_APPLIED = -700
    UNAPP = 700 -200 -500 = 0
    APP = 200 + 500 = 700
    Statuses of these records can be:-
    UNAPP - Unapplied
    APP - Applied
    ACC - On Account
    UNID - Unidentified (Customer Not known)
    이러한 record내역은 invoice/credit/receipt에 있는 Transaction History form에서 확인할 수 있다.
    2.5 AR_PAYMENT_SCHEDULE (Invoice)
    Receipt이 특정 invoice에 apply되면, invoice에 대한 Payment Schedule record가 update된다.
    remaining amount field 값은 Payment금액만큼 줄어들게 된다.
    만약, remaining amount가 "0"가 되면, invoice Payment schedule은 closed상태가 된다.
    예를들어, Receipt금액 "200"이 "1175" invoice금액(Tax금액 175가 포함된)에 apply되었다면, Invoice의 Payment Schedule은 아래와 같이 조정된다.
    Before After
    AMOUNT_DUE_REMAINING 1175.00 975.00
    AMOUNT_LINE_ITEMS_REMAINING 1000.00 800.00
    TAX_REMAINING 175.00 175.00
    FREIGHT_REMAINING 0.00 0.00
    Note that receipts are applied in a fixed sequence:-
    1. Line Amounts
    2. Tax Amounts
    3. Freight Amounts
    ie The TAX_REMAINING figure will only start to decrease when the
    AMOUNT_LINE_ITEMS_REMAINING is zero.
    Reference Documents
    Note : 29277.1 & 29278.1

    Hi,
    This query works fine for me:
    SELECT CR.CASH_RECEIPT_ID,
                CR.RECEIPT_NUMBER,
                CR.RECEIPT_DATE,
                CR.CURRENCY_CODE,
                DECODE ( CR.TYPE, 'MISC', NULL, NVL (SUM (DECODE (RA.STATUS, 'ACC', NVL (RA.AMOUNT_APPLIED, 0), 0)), 0)) ON_ACCOUNT_AMOUNT
             FROM AR_RECEIVABLE_APPLICATIONS_ALL RA,
                AR_CASH_RECEIPTS_ALL CR,
                AR_RECEIPT_METHODS RM
          WHERE RA.CASH_RECEIPT_ID = CR.CASH_RECEIPT_ID
                AND CR.RECEIPT_METHOD_ID = RM.RECEIPT_METHOD_ID
                AND CR.ORG_ID = <org_id>
          GROUP BY CR.CASH_RECEIPT_ID,
                CR.RECEIPT_DATE,
                CR.RECEIPT_NUMBER,
                RM.NAME,
                CR.CURRENCY_CODE,
                CR.TYPE order by receipt_date desc
    Let me know if it worked.
    Octavio

  • How history tables like MBEWH applied to Inventory cube 0IC_C03

    Hi BW Gurus,
    Need your advice on this. How actually we can applied history tables like MBEWH, MARCH, MCHBH, MKOLH, MSKUH link with the cube? Is it create as master data or create customer exist to 2LIS_03_BF data source?
    As my concern is how actually MonthYear data in this history table can map to transaction cube.
    Appreciate your help. Thanks.
    Regards,
    Jeff ([email protected])

    HI  Ramanjaneyulu ,
    Follow these steps & PDF FILE AT THE END.
    1. Activation:
    Activate the extract structure MC03BF0 for the corresponding DataSources
    2LIS_03_BX/2LIS_03_BF in the LO cockpit (transaction code in R/3: LBWE).
    2. Initialization:
    Initialization of the current stock (opening balance) in the R/3 source system with
    DataSource 2LIS_03_BX (transaction code in R/3: MCNB)
    Data is added to the setup table MC03BX0SETUP.
    3. Setup of statistical data:
    You can find the setup of statistical data under transaction SBIW in the R/3 system or use transaction code OLI1BW for material movement and transaction OLIZBW revolutions.
    4. Loading the opening stock balance (2LIS_03_BX):
    In the InfoPackage, choose the upload mode “Create opening balance”.
    5. Compressing the request:
    Compress the request containing the opening stock that was just uploaded. Make sure the "No marker update" indicator is not set. Please consider note very carefully 643687 before you carry out the compression of requests in stock InfoCubes.
    6. Loading the historical movements:
    Choose the upload mode "Initializing the delta process".
    7. Compress the request:
    After successfully uploading the historical material movements, the associated request has to be compressed. You must make sure the "No marker update"
    indicator is set.
    8. Start the unserialized V3 update or queued delta control run:
    Transaction code: SBIW. Data is written from the extraction queue or central update table into the delta queue (transaction code in R/3: RSA7). Data is now available for extraction for BI system.
    9. Start delta uploads:
    Successive (for example, daily) delta uploads can be started with the DataSource
    2LIS_03_BF from this point in time on.
    <b>PDF ON INVENTORY:</b>
    https://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/docs/library/uuid/f83be790-0201-0010-4fb0-98bd7c01e328
    Thanks,
    kiran

  • Big history table based on SCD2

    Ola,
    Has anyone of you ever experienced difficulties running millions of records through a SCD2 mapping? I created a couple of history tables and created mappings to fill them, based on SCD2-method. When I tested the mappings with a subset of data (10.000 - 40-000 rows), it all went OK.
    Now I test the mapping with the full data set and three of the most large tables fail. The largest table is 23.7 million records. The smallest of the failing ones is 17.8 million. I get an error like this:
    ORA-06502: PL/SQL: numeric or value error: character string buffer too small ORA-06512: at "OWNER_OWR.WB_RT_MAPAUDIT", line 1762 ORA-06512: at "OWNER_OWR.WB_RT_MAPAUDIT", line 2651 ORA-06512: at "OWNER_LCN.E_ASL_SERVICE_HIST_LASH", line 3159 ORA-01555: snapshot too old: rollback segment number 2 with name "_SYSSMU2$" too small ORA-06512: at "OWNER_LCN.E_ASL_SERVICE_HIST_LASH", line 3680 ORA-06512: at "OWNER_LCN.E_ASL_SERVICE_HIST_LASH", line 4229 ORA-06512: at line 1
    Only thing I changed is the dataset. Nothing else...
    Does the 'snapshot too old' message mean that it takes too much time to finish the mapping process?
    Anyone any clue?
    Kind regards,
    Moscowic

    Though I havent faced the error while using OWB, saw this error on other occasaions when the the transaction was pretty large or if the UNDO segment was too small and couldnt hold the rollback information of a transaction.
    Check a couple of things...
    1. if you are running mapping it in a SET based mode with large data, u r likely to hit this error.
    2. Ask your DBA to lookinto the UNDO segment/tablesapce, if in case any fragmentation issues.
    Hope this helps.
    Nat

  • Best practices for creating and querying a history table?

    Suppose I have a table of name-value pairs, and I want to keep track of changes to them so that I can query the value of any pair at any point in time.
    A direct approach would be to use a schema like this:
    CREATE TABLE NAME_VALUE_HISTORY (
      NAME      VARCHAR2(...),
      VALUE     VARCHAR2(...),
      MODIFIED DATE
    );When a name-value pair is updated, a new row is added to this table with the date of the change.
    To determine the value associated with a name at a particular point in time, one uses a query like:
      SELECT * FROM NAME_VALUE_HISTORY
      WHERE NAME = :name
        AND MODIFIED IN (SELECT MAX(MODIFIED)
                        FROM NAME_VALUE_HISTORY
                        WHERE NAME = :name AND MODIFIED <= :time)My question is: is there a better way to accomplish this? What indexes/hints would you recommend?
    What about a two-table approach like this one? http://pratchev.blogspot.com/2007/05/keeping-history-data-in-sql-server.html
    Edited by: user10936714 on Aug 9, 2012 8:35 AM

    user10936714 wrote:
    There is one advantage... recording the change of a value is just one insert, and it is also atomic without the use of transactions.At the risk of being dumb, why is that an advantage? Oracle always and everywhere uses transactions so it's not like you're avoiding some overhead by not using transactions.
    If, for instance, the performance of reading the value of a name at a point in time is not important, then you can get by with just using one table - the history table.If you're not overly concerned with the performance implications of having the current data and the history data in the same table, rather than rolling your own solution, I'd be strongly tempted to use Workspace Manager to let Oracle keep track of the changes.
    You can create a table, enable versioning, and do whatever DML operations you'd like
    SQL> create table address(
      2    address_id number primary key,
      3    address    varchar2(100)
      4  );
    Table created.
    SQL> exec dbms_wm.enableVersioning( 'ADDRESS', 'VIEW_WO_OVERWRITE' );
    PL/SQL procedure successfully completed.
    SQL> insert into address values( 1, 'First Address' );
    1 row created.
    SQL> commit;
    Commit complete.
    SQL> update address
      2     set address = 'Second Address'
      3   where address_id = 1;
    1 row updated.
    SQL> commit;
    Commit complete.Then you can either query the history view
    SQL> ed
    Wrote file afiedt.buf
      1  select address_id, address, wm_createtime
      2*   from address_hist
    SQL> /
    ADDRESS_ID ADDRESS                        WM_CREATETIME
             1 First Address                  09-AUG-12 01.48.58.566000 PM -04:00
             1 Second Address                 09-AUG-12 01.49.17.259000 PM -04:00Or, even cooler, you can go back to an arbitrary point in time, run a query, and see the historical information. I can go back to a point between the time that I committed the first change and the second change, query the ADDRESS view, and see the old data. This is invaluable if you want to take existing queries and/or reports and run them as of certain dates in the past when you're trying to debug a problem.
    SQL> select *
      2    from address;
    ADDRESS_ID ADDRESS
             1 First AddressYou can also do things like set savepoints which are basically named points in time that you can go back to. That lets you do things like create a savepoint for the data as soon as month-end processing is completed so you can easily go back to "July Month End" without needing to figure out exactly what time that occurred. And you can have multiple workspaces so different users can be working on completely different sets of changes simultaneously without interfering with each other. This was actually why Workspace Manager was originally created-- to allow users manipulating spatial data to have extremely long-running transactions that could span days or months-- and to be able to switch back and forth between the current live data and the data in each of these long-running scenarios.
    Justin

  • Cost to change hash partition key column in a history table

    Hi All,
    I have the following scenario.
    We have a history table in production which has 16 hash partitions on the basis of key_column.
    But the nature of data that we have in history table that has 878 distinct values of the key_column and about 1000 million data and all partitons are in same tablespace.
    Now we have a Pro*C module which purges data from this history table in the following way..
    > DELETE FROM hsitory_tab
    > WHERE p_date < (TO_DATE(sysdate+1, 'YYYYMMDD') - 210)
    > AND t_date < (TO_DATE(sysdate+1, 'YYYYMMDD') - 210)
    > AND ROWNUM <= 210;
    Now (p_date,t_data are one of the two columns in history table) data is deleted using thiese two date column conditions but key_column for partition is different.
    So as per aboove statement this history table containd 6 months data.
    DBA is asking to change this query and use partiton date wise.Now will it be proper to change the partition key_column (the existing hash partiton key_column >have 810 distinct values) and what things we need to cosider to calculate cost behind this hash partition key_column cahange(if it is appropriate to change >partition )key_column)Hope i explained my problem clearly and waiting for your suggestions .
    Thanks in advance.

    Hi Sir
    Many thanks for the reply.
    For first point -
    we are in plan to move the database to 10g after a lot of hastle between client.For second point -
    If we do partition by date or week we will have 30 or 7 partitions .As suggested by you as we have 16 partitions in the table best approach would be to have >partition by week then we will have 7 partitions and then each query will heat 7 partitions .For third point -
    Our main aim to reduce the timings of a job(a Pro*C program) which contains the following delete query to delete data from a history table .So accroding to the >query it is deleting data every day for 7 months and while deleting it it queries this hug etable by date.So in this case hash partition or range partiton or >hash/range partition which will be more suitable.
    DELETE FROM hsitory_tab
    WHERE p_date < (TO_DATE(sysdate+1, 'YYYYMMDD') - 210)
    AND t_date < (TO_DATE(sysdate+1, 'YYYYMMDD') - 210)
    AND ROWNUM <= 210;I have read in hash partition is used so that data will be evenly distributed in all partitions (though it depends on nature of data).In my case i want some suggestion from you to take the best approach .

  • Create History Table from Main

    I'm seeking help from the experts because I'm far from an expert and I have been unsuccessful at figuring this out on my own.
    So far I've created a history table which is to keep all our data history from our main table. It is almost the same table, but with a few added columns to better keep records. The purpose of creating the table is to keep from having so much data in our main table so it will cut down on data query times.
    This, to me, is a very complicated SQL statement. I'm trying to use an INSERT statement to do this. But I'm updating the history table from multiple tables. An example of what I'm trying is:
    INSERT INTO history_table a (column1, column2, column3, etc. )
    SELECT (b.column1, b.column2, c.title||' '||c.l_name||', '||c.f_name, b.column4, etc.)
    FROM main_table b, code_id_table c
    WHERE b.column3 = c.column1
    The problem is when I encounter null values in table3 c. Since I'm concatenating a few columns into one, if any of those columns are null, I get an error since it doesn't know what data to pull. I want it to just put NULL values where it's pulling NULL values. I'm pretty sure it will work with an IF THEN statement, but I'm not sure exactly how to handle it or if I'm even going at this with the right approach. The goal is the create a history table with a little more information than the main table so we have to pull information from multiple tables into the history table and get around the null values.
    I hope I've made sense with any of this. If someone has some ideas, advice, or examples for me I'd greatly appreciate it. Thanks for your time.
    -FC1

    Oh I apologize. I'm running version 8i at the moment but will be upgrading to 10g within the next few weeks.
    -FC1

  • How to find the deleted data in tables

    guys,
    how to find the deleted data in tables example: i want to see whether anyone deleted data in MB5B report tables like mbew, etc.,
    regards,

    Hi,
    MBEWH is actually the history table of MBEW. It will record all the changes. As I have told you earlier if you have deleted the record dirctly from the table then it will not come even in the table MBEWH
    That means no changes have been made.
    regards

  • History tables on 8.8

    Guys,
    We've got various add-on solutions, and reports, that examine the history tables for various B1 objects
    (documents, Business Partners, etc).
    Up until 8.8, the history tables always stored the current revision of a record as well as the historical
    revisions. In 8.8, it seems that the current revision is no longer stored in the history tables - the highest
    revision stored is the one previous to the current state.
    This has quite an impact on our add-ons and reports - does anyone know if this behaviour is by design,or a bug in 8.8?

    For example, if your create a Sales Order under 2005 or 2007, the ordr table is populated with the sales order and its values. Also a record is created in the adoc table with a loginstanc of 1, with those same (current values). Now edit the SO, (by altering the comments/remarks field for instance). What happens now is that the record in the ordr table reflects your change, as you would expect. In the adoc table, a new record with a loginstanc of 2 is created, containing these current values, so you now have two records in adoc, the first being the original data, the second being the current data.
    Now, do the same in 8.8 (I have PL06 installed). When you create the SO, the order table is populated as you would expect. However, no record is created in adoc at all. When you edit the SO, a record is created in adoc with a loginstanc of 1 which contains the original data.
    Now, we have add ons and reports that work on the historical data (not just for documents, for other objects too) that rely on thebehaviour shown in 2005/2007 as it means we don't have to link back to the other tables to get the current data - which is a big bonus when working with adoc, otherwise you have to join dependant on the value of objtype.
    If this has changed by design in 8.8 it's going to cause us quite a bit of pain.
    I can't find any info on this in the 8.8 documents, nor in the list of changes in the database/SDK for 8.8.
    I just want to know if this is by design, or it's a bug in the ramp-up versions of 8.8.
    I'm also not sure what's going to happen when we upgrade a 2007 DB to 8.8 - will it strip out the current revisions from teh history tables? I might try that today.

  • Sales order changes history table

    hi.........
    i wann field for user name from sales order change history table. i hv tried CDHDR and CDPOS, but i cound't get the exact link in those tables.
    will u tel me any other table, so that i can get this field by passing sales order ?

    Hi subharao,
    Go though this program.
    REPORT zmm_rep_poh NO STANDARD PAGE HEADING LINE-SIZE 250 LINE-COUNT 65.
    TABLES: cdhdr,cdpos,ekko,ekpo.
    TYPE-POOLS : slis.
    DATA       : t_fieldalv     TYPE slis_t_fieldcat_alv.
    DATA       : import_variant LIKE disvariant.
    DATA       : xrepid         LIKE sy-repid.
    DATA       : layout         TYPE slis_layout_alv.
    DATA: BEGIN OF itab OCCURS 0,
            fname(40) ,
            objectid(10),
            changenr(10) ,
            value_new(10),
            value_old(10),
            unit_old(10),
            unit_new(10),
            cuky_old(10),
            cuky_new(10),
            key(5),
            username(10),
            udate LIKE cdhdr-udate,
            utime LIKE cdhdr-utime,
          END OF itab.
    DATA iebeln(15).
    DATA: BEGIN OF itab1 OCCURS 0,
            username(10),
            udate LIKE cdhdr-udate,
            changenr(10),
            utime LIKE cdhdr-utime,
          END OF itab1.
    DATA: BEGIN OF itab3 OCCURS 0.
            INCLUDE STRUCTURE itab.
    DATA: END OF itab3.
    DATA iekko LIKE ekko OCCURS 0 WITH HEADER LINE.
    *Select Option
    SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE text-001.
    SELECT-OPTIONS : s_ebeln FOR ekpo-ebeln OBLIGATORY,
                     s_ekorg FOR ekko-ekorg NO INTERVALS DEFAULT '77IN',
                     s_bukrs FOR ekko-bukrs NO INTERVALS DEFAULT '77IN'.
    SELECTION-SCREEN END OF BLOCK b1.
    *INITIALIZATION.
    for alv field catalog definition.
      PERFORM initial_alv_fieldcat CHANGING t_fieldalv[].
    START-OF-SELECTION.
      SELECT * INTO iekko
      FROM ekko
      WHERE ebeln IN s_ebeln AND ekorg IN s_ekorg AND bukrs IN s_bukrs.
        APPEND iekko.
      ENDSELECT.
      LOOP AT iekko.
        SELECT username udate changenr utime
        INTO   (itab1-username,itab1-udate,
               itab1-changenr,itab1-utime)
        FROM  cdhdr
        WHERE objectid EQ iekko-ebeln.
          APPEND itab1.
        ENDSELECT.
      ENDLOOP.
      LOOP AT itab1.
        SELECT objectid changenr fname value_old value_new unit_old unit_new
               cuky_old cuky_new
        INTO  (itab-objectid, itab-changenr, itab-fname,
              itab-value_old,itab-value_new ,itab-unit_old, itab-unit_new,
              itab-cuky_old,itab-cuky_new)
        FROM  cdpos
        WHERE changenr = itab1-changenr.
          IF sy-subrc = 0.
            itab-username = itab1-username.
            itab-udate    = itab1-udate.
            itab-utime    = itab1-utime.
            APPEND itab.
          ENDIF.
        ENDSELECT.
      ENDLOOP.
    delete itab where fname eq 'KEY'.
      sort itab by fname.
    delete ADJACENT DUPLICATES FROM itab comparing all fields.
      LOOP AT itab.
        IF itab-fname = 'ZTERM'.
           itab-fname = 'Payment Terms'.
          MODIFY itab.
        ELSEIF itab-fname = 'AEDAT'.
               itab-fname = 'Date'.
          MODIFY itab.
        ELSEIF itab-fname = 'EFFWR'.
               itab-fname = 'Effective Value'.
          MODIFY itab.
        ELSEIF itab-fname = 'MENGE'.
               itab-fname = 'PO Quantity'.
          MODIFY itab.
        ELSEIF itab-fname = 'BRTWR'.
               itab-fname = 'Gross Order Value'.
          MODIFY itab.
        ELSEIF itab-fname = 'NETWR'.
               itab-fname = 'Net Order Value'.
          MODIFY itab.
        ELSEIF itab-fname = 'PROCSTAT'.
               itab-fname = 'Purchasing Doc processing state'.
          MODIFY itab.
        ELSEIF itab-fname = 'FRGSX'.
               itab-fname = 'Release Strategy'.
          MODIFY itab.
        ELSEIF itab-fname = 'FRGKE'.
               itab-fname = 'Release Ind. Pur. Doc'.
          MODIFY itab.
        ELSEIF itab-fname = 'ZBD1P'.
               itab-fname = 'Cash Discount Perc 1'.
          MODIFY itab.
        ELSEIF itab-fname = 'ZBD1T'.
               itab-fname = 'Cash Discount Days'.
          MODIFY itab.
        ELSEIF itab-fname = 'ZBD2T'.
               itab-fname = 'Cash Discount Days'.
          MODIFY itab.
              ELSEIF itab-fname = 'KEY'.
               itab-fname = 'Item Entered'.
          MODIFY itab.
        ENDIF.
      ENDLOOP.
      PERFORM alv_grid_display.
    *&      Form  alv_grid_display
          text
    -->  p1        text
    <--  p2        text
    FORM alv_grid_display .
      DATA  : gt_event  TYPE slis_t_event.
      DATA  : dbcnt TYPE i.
      DATA  : dbcntr(10) TYPE c.
      DATA  : title(100) TYPE c.
      CLEAR : dbcnt,dbcntr,title.
      DESCRIBE TABLE itab LINES dbcnt.
      dbcntr = dbcnt.
      CONCATENATE 'NO.OF ENTRIES : ' dbcntr INTO title SEPARATED BY space.
      sy-title = title.
      CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'
        EXPORTING
          i_callback_program = sy-repid
          is_layout          = layout
          it_fieldcat        = t_fieldalv[]
          i_save             = 'A'
          i_grid_title       = 'Purchase Order Amendment Details'
        TABLES
          t_outtab           = itab
        EXCEPTIONS
          program_error      = 1
          OTHERS             = 2.
    ENDFORM.                    " alv_grid_display
    *&      Form  initial_alv_fieldcat
          text
         <--RT_FIELDCAT  text
    FORM initial_alv_fieldcat  CHANGING rt_fieldcat TYPE slis_t_fieldcat_alv.
      DATA       : ls_fieldcat TYPE slis_fieldcat_alv .
      DATA       : cntr TYPE i VALUE 1.
      CLEAR ls_fieldcat.
      cntr = cntr + 1.
      ls_fieldcat-col_pos   = 1.
      ls_fieldcat-fieldname = 'USERNAME'.
      ls_fieldcat-seltext_l = 'UNAME'.
      ls_fieldcat-do_sum    = 'X'.
      APPEND ls_fieldcat TO rt_fieldcat.
      CLEAR ls_fieldcat.
      cntr = cntr + 1.
      ls_fieldcat-col_pos   = 2.
      ls_fieldcat-fieldname = 'UDATE'.
      ls_fieldcat-seltext_l = 'UDATE'.
      ls_fieldcat-do_sum    = 'X'.
      APPEND ls_fieldcat TO rt_fieldcat.
      CLEAR ls_fieldcat.
      cntr = cntr + 1.
      ls_fieldcat-col_pos   = 3.
      ls_fieldcat-fieldname = 'UTIME'.
      ls_fieldcat-seltext_l = 'UTIME'.
      ls_fieldcat-do_sum    = 'X'.
      APPEND ls_fieldcat TO rt_fieldcat.
      CLEAR ls_fieldcat.
      cntr = cntr + 1.
      ls_fieldcat-col_pos   = 4.
      ls_fieldcat-fieldname = 'OBJECTID'.
      ls_fieldcat-seltext_l = 'PO Number'.
      ls_fieldcat-do_sum    = 'X'.
      APPEND ls_fieldcat TO rt_fieldcat.
      CLEAR ls_fieldcat.
      cntr = cntr + 1.
      ls_fieldcat-col_pos   = 5.
      ls_fieldcat-fieldname = 'FNAME'.
      ls_fieldcat-seltext_l = 'Field Name'.
      ls_fieldcat-do_sum    = 'X'.
      APPEND ls_fieldcat TO rt_fieldcat.
      CLEAR ls_fieldcat.
      cntr = cntr + 1.
      ls_fieldcat-col_pos   = 6.
      ls_fieldcat-fieldname = 'VALUE_OLD'.
      ls_fieldcat-seltext_l = 'Old Value'.
      ls_fieldcat-do_sum    = 'X'.
      APPEND ls_fieldcat TO rt_fieldcat.
      CLEAR ls_fieldcat.
      cntr = cntr + 1.
      ls_fieldcat-col_pos   = 7.
      ls_fieldcat-fieldname = 'VALUE_NEW'.
      ls_fieldcat-seltext_l = 'New Value '.
      ls_fieldcat-do_sum    = 'X'.
      APPEND ls_fieldcat TO rt_fieldcat.
      CLEAR ls_fieldcat.
      cntr = cntr + 1.
      ls_fieldcat-col_pos   = 8.
      ls_fieldcat-fieldname = 'UNIT_OLD'.
      ls_fieldcat-seltext_l = 'Old Unit'.
      ls_fieldcat-do_sum    = 'X'.
      APPEND ls_fieldcat TO rt_fieldcat.
      CLEAR ls_fieldcat.
      cntr = cntr + 1.
      ls_fieldcat-col_pos   = 9.
      ls_fieldcat-fieldname = 'UNIT_NEW'.
      ls_fieldcat-seltext_l = 'New Unit'.
      ls_fieldcat-do_sum    = 'X'.
      APPEND ls_fieldcat TO rt_fieldcat.
      CLEAR ls_fieldcat.
      cntr = cntr + 1.
      ls_fieldcat-col_pos   = 10.
      ls_fieldcat-fieldname = 'CUKY_OLD'.
      ls_fieldcat-seltext_l = 'Old Cuky'.
      ls_fieldcat-do_sum    = 'X'.
      APPEND ls_fieldcat TO rt_fieldcat.
      CLEAR ls_fieldcat.
      cntr = cntr + 1.
      ls_fieldcat-col_pos   = 11.
      ls_fieldcat-fieldname = 'CUKY_NEW'.
      ls_fieldcat-seltext_l = 'New Cuky'.
      ls_fieldcat-do_sum    = 'X'.
      APPEND ls_fieldcat TO rt_fieldcat.
      layout-zebra = 'X'.
      layout-colwidth_optimize = 'X'.
    ENDFORM.                    " initial_alv_fieldcat
    *********Rewards some points.
    Rgds,
    P.Naganjana Reddy

  • Clear History Table Every 6 Months - Review my PL/SQL Snippet

    The code below clears employees history table every 6 months. The code below executes fine, i'm just trying to make
    sure if there is any logic error or not, I don't think so, but i would like to confirm from you.
    -- This table holds delete date that deletes records from employee and customer history tables
    CREATE TABLE historyDeletionDate (deleteHistoryDate DATE);
    CREATE OR REPLACE PROCEDURE clear_emphistory
    IS
       dateOfDeletion DATE;
    BEGIN
       BEGIN
          SELECT deleteHistoryDate
            INTO dateOfDeletion
            FROM historyDeletionDate;
       EXCEPTION
          WHEN NO_DATA_FOUND THEN
             dateOfDeletion := SYSDATE;
       END;
       IF TRUNC(dateOfDeletion) <= TRUNC(SYSDATE) THEN
          EXECUTE IMMEDIATE 'truncate table CUSTOMERHISTORY';
          EXECUTE IMMEDIATE 'PURGE RECYCLEBIN';
          UPDATE historyDeletionDate SET deleteHistoryDate = ADD_MONTHS(SYSDATE, 6);
       END IF;
    END;
    /

    Hi,
    It look good to me: efficient and clear.
    Production code should have some comments in it. Pretend that someone (someone you like) has to take over your job without any training on you code. What would that person find useful?
    Instead of a one-row, one column table just to hold the next scheduled deleteHistoryDate, consider having a multi-row, 2-column table that also serves as a log of when deletions were actually done. You could have a scheduledDate column that is entered when the job is schduled, and a completedDate column that is originally NULL, but filled in when the job completes. The firest query would be:
    SELECT  scheduledDate
      INTO  dateOfDeletion
      FROM  historyDeletionDate
    WHERE  completedDate     IS NULL;

Maybe you are looking for