PL/SQL LOOP MONTH

One more favor, PLEASe...
CREATE TABLE USR_FAC
FACILITY_ID VARCHAR2(16),
FACILITY_NAME VARCHAR2(30),
DOCTOR_ID VARCHAR2(16),
EFFECTIVE_DATE DATE,
STATUS VARCHAR2(1)
INSERT INTO usr_fac (FACILITY_ID, FACILITY_NAME,doctor_id, effective_date, STATUS) VALUES ('F1001','UNC_HOSPITAL','D1001', '01-JAN-2009','1');
INSERT INTO usr_fac (FACILITY_ID, FACILITY_NAME,doctor_id, effective_date, STATUS) VALUES ('F1001','UNC_HOSPITAL','D1001', '01-OCT-2009','0');
INSERT INTO usr_fac (FACILITY_ID, FACILITY_NAME,doctor_id, effective_date, STATUS) VALUES ('F1002','UNC_HOSPITAL_2','D1001', '01-OCT-2009','1');
INSERT INTO usr_fac (FACILITY_ID, FACILITY_NAME,doctor_id, effective_date, STATUS) VALUES ('F1003','UNC_HOSPITAL_3','D1002', '01-JAN-2010','1');
INSERT INTO usr_fac (FACILITY_ID, FACILITY_NAME,doctor_id, effective_date, STATUS) VALUES ('F1003','UNC_HOSPITAL_3','D1003', '01-FEB-2010','1');
COMMIT;
Here status: 1 - ACTIVE and 0 - TERMINATED.
Similarly, I want to have monthly rows when the docotor is active.
So D1001 should have 1 row each of the month- from 01-jan-2009 to 01-oct-2009 with same facility_id and name.
When he gets terminated, one row is fine.
When he becomes active again, it should restart monthly rows up to sysdate.
THIS WILL BE GREAT HELP.
THANKS

Hi,
788729 wrote:
People are mess. Alright, I think I know what's going on now.
One issue I am having not because of our IS dep't but our iffy Config dep't.
So for few record like 78 to be exact, either the effective date of status = 1 or effective date of status = 0 is not consistent meaning date is not always '01' in 'DD-MON-YYYY' = '01-JAN-2010'. This is a big issue which I have addressed to config but, meanwhile is there a quick fix to this?
In above case, our first sub-query calculated incorrect MONTHS_NEEDED. For example, IF Config has term doctor on 5/5/2010, then that (DATE - 1) function will keep that provider active in May but infact, he should not be active 4/1/2010.Did you mean "he should not be active <b>5</b>/1/2010"?
That is, if a Termination row is dated May, 1, then you want to insert an Active row for April 1, don't you? If the Termination date is a little later (that is May 5), wouldn't you still want an Active row for April 1?
The query I posted yesterday added
new rows for the 1st of each month up to, but not including, the day of the termination. I think what you're saying now is that you want
new rows for the 1st of each month up to, but not including, the month of the termination.
If that's correct, then just change the place where months_needed is calculated. Instead of subtracting 1 day from the termination date, subtract 1 month .
INSERT INTO  usr_fac
(       facility_id, facility_name, doctor_id
,      effective_date
,     status               -- If needed
WITH     got_months_needed     AS
     SELECT    a.facility_id, a.facility_name, a.doctor_id, a.effective_date
--     ,       MONTHS_BETWEEN ( TRUNC ( NVL ( MIN (t.effective_date) - 1          -- Old way, August 16
     ,       MONTHS_BETWEEN ( TRUNC ( NVL ( ADD_MONTHS ( MIN (t.effective_date)     -- New way, August 17
                                                    , -1                 -- New way  
                                       )                     -- New way                    
                                              , SYSDATE
                             , 'MONTH'
                        , a.effective_date
                        )          AS months_needed
     FROM           usr_fac     a
     LEFT OUTER JOIN  usr_fac     t     ON     a.facility_id       = t.facility_id
                                       AND     a.facility_name       = t.facility_name     -- If needed
                              AND     a.doctor_id       = t.doctor_id
                              AND     a.effective_date  < t.effective_date
                              AND     0            = t.status
     WHERE     a.status          = 1
     GROUP BY  a.facility_id, a.facility_name, a.doctor_id, a.effective_date
,     cntr          AS
     SELECT     LEVEL     AS n
     FROM     (
              SELECT  MAX (months_needed)     AS max_months_needed
              FROM    got_months_needed
     CONNECT BY     LEVEL <= max_months_needed
SELECT     m.facility_id, m.facility_name, m.doctor_id
,      ADD_MONTHS ( m.effective_date
             , c.n
             )          AS effective_date
,     '1'                 -- If needed
FROM     got_months_needed  m
JOIN     cntr             c     ON     c.n     <= m.months_needed
;Of course, you don't need the commented-out line that says "Old way", or the comments that say "New way"; I just added them so that you could see where I changed the statement. Except for the computation of months_needed, the statement is the same. (Actually, I got rid of the ORDER BY clause; that was just a relic of the testing process. It only wastes time in an acutal INSERT.)
Given your new sample data, the staement above leaves the usr_fac table looking like this:
FACILITY_ID  FACILITY_NAME   DOCTOR_ID EFFECTIVE_D STATUS
F1001        UNC_HOSPITAL    D1001     01-Jan-2009 1
F1001        UNC_HOSPITAL    D1001     01-Feb-2009 1
F1001        UNC_HOSPITAL    D1001     01-Mar-2009 1
F1001        UNC_HOSPITAL    D1001     01-Apr-2009 1
F1001        UNC_HOSPITAL    D1001     01-May-2009 1
F1001        UNC_HOSPITAL    D1001     01-Jun-2009 1
F1001        UNC_HOSPITAL    D1001     01-Jul-2009 1
F1001        UNC_HOSPITAL    D1001     01-Aug-2009 1
F1001        UNC_HOSPITAL    D1001     01-Sep-2009 1
F1001        UNC_HOSPITAL    D1001     01-Oct-2009 0
F1002        UNC_HOSPITAL_2  D1001     01-Oct-2009 1
F1002        UNC_HOSPITAL_2  D1001     01-Nov-2009 1
F1002        UNC_HOSPITAL_2  D1001     01-Dec-2009 1
F1002        UNC_HOSPITAL_2  D1001     01-Jan-2010 1
F1002        UNC_HOSPITAL_2  D1001     01-Feb-2010 1
F1002        UNC_HOSPITAL_2  D1001     01-Mar-2010 1
F1002        UNC_HOSPITAL_2  D1001     01-Apr-2010 1
F1002        UNC_HOSPITAL_2  D1001     05-May-2010 0
F1003        UNC_HOSPITAL_3  D1002     01-Jan-2010 1
F1003        UNC_HOSPITAL_3  D1002     01-Feb-2010 1
F1003        UNC_HOSPITAL_3  D1002     01-Mar-2010 1
F1003        UNC_HOSPITAL_3  D1002     01-Apr-2010 1
F1003        UNC_HOSPITAL_3  D1002     01-May-2010 1
F1003        UNC_HOSPITAL_3  D1002     01-Jun-2010 1
F1003        UNC_HOSPITAL_3  D1002     01-Jul-2010 1
F1003        UNC_HOSPITAL_3  D1002     01-Aug-2010 1
F1003        UNC_HOSPITAL_3  D1003     01-Feb-2010 1
F1003        UNC_HOSPITAL_3  D1003     01-Mar-2010 1
F1003        UNC_HOSPITAL_3  D1003     01-Apr-2010 1
F1003        UNC_HOSPITAL_3  D1003     01-May-2010 1
F1003        UNC_HOSPITAL_3  D1003     01-Jun-2010 1
F1003        UNC_HOSPITAL_3  D1003     01-Jul-2010 1
F1003        UNC_HOSPITAL_3  D1003     01-Aug-2010 1That seems to be what you want, but "Esse non videre", as the Tar Heels say. Correct me if you need different results.

Similar Messages

  • PL/SQL LOOP or INSERT MONTH

    I have a table below that has START_DATE and END_DATE for each record but not individual row for each month. So, a record can have 6 months payment with start date - '20100101' to end_date 20100630.
    I need to find out payment for each month for recon.
    I want to add that month field and keep everything else exactly the same as what's in table.
    For above example it should add
    01-JAN-2010 ................................................ <--- everything else same
    01-FEB-2010 ........................
    |
    |
    |
    01-JUN-2010 ..........................................................
    The helpful fields are START_DATE, END_DATE, NO_OF_MONTHS1 and NO_MONTHS_2. Somethimes, NO_MONTH1 and NO_MONTHS_2 differ. Normally whe they differ, one is 00.
    --oracle 10g
    --DROP TABLE PAYMENTS;
    CREATE TABLE PAYMENTS
    CMPNY VARCHAR2,
    S_ID VARCHAR2,
    NO_MONTHS_1 VARCHAR2,
    NO_MONTHS_2 VARCHAR2,
    ADJ_CODE VARCHAR2,
    START_DATE VARCHAR2,
    END_DATE VARCHAR2,
    AMOUNT NUMBER
    INSERT INTO PAYMENTS (CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('C001','S001','06','06','20','20100101','20100630','30');
    INSERT INTO PAYMENTS (CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('C001','S001','04','04','12','20090101','20090430','50');
    INSERT INTO PAYMENTS (CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('C002','S001','02','02','20','20090801','20100930','100');
    INSERT INTO PAYMENTS (CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('C002','S002','02','02','20','20090801','20100930','100');
    INSERT INTO PAYMENTS (CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('C001','S002','01','01','12','20090101','20090131','50');
    INSERT INTO PAYMENTS (CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('C001','S001','00','04','18','20090101','20090430','50');
    INSERT INTO PAYMENTS (CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('C001','S003','00','02','12','20090501','20090731','50');
    INSERT INTO PAYMENTS (CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('C001','S004','01','01','12','20090101','20090131','50');
    commit;
    RESULTS should be something like
    CREATE TABLE PAYMENTS1
    ELIGIBLE_MONTH DATE,
    CMPNY VARCHAR2,
    S_ID VARCHAR2,
    NO_MONTHS_1 VARCHAR2,
    NO_MONTHS_2 VARCHAR2,
    ADJ_CODE VARCHAR2,
    START_DATE VARCHAR2,
    END_DATE VARCHAR2,
    AMOUNT NUMBER
    commit;
    --BELOW IS AN EXAMPLE OF HOW THE SOLUTION SHOULD COMEOUT FOR FIRST 3 RECORD IN ABOVE TABLE
    ---for first record in above table, it should create 6 rows, and apply eligible_month to it
    INSERT INTO PAYMENTS (ELIGIBLE_MONTH, CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('01-JAN-2010','C001','S001','06','06','20','20100101','20100630','30');
    INSERT INTO PAYMENTS (ELIGIBLE_MONTH, CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('01-FEB-2010','C001','S001','06','06','20','20100101','20100630','30');
    INSERT INTO PAYMENTS (ELIGIBLE_MONTH, CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('01-MAR-2010','C001','S001','06','06','20','20100101','20100630','30');
    INSERT INTO PAYMENTS (ELIGIBLE_MONTH, CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('01-APR-2010','C001','S001','06','06','20','20100101','20100630','30');
    INSERT INTO PAYMENTS (ELIGIBLE_MONTH, CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('01-MAY-2010','C001','S001','06','06','20','20100101','20100630','30');
    INSERT INTO PAYMENTS (ELIGIBLE_MONTH, CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('01-JUN-2010','C001','S001','06','06','20','20100101','20100630','30');
    ---IT SHOULD CREATE 4 ROWS
    INSERT INTO PAYMENTS (ELIGIBLE_MONTH, CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('01-JAN-2009','C001','S001','04','04','12','20090101','20090430','50');
    INSERT INTO PAYMENTS (ELIGIBLE_MONTH, CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('01-FEB-2009','C001','S001','04','04','12','20090101','20090430','50');
    INSERT INTO PAYMENTS (ELIGIBLE_MONTH, CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('01-MAR-2009','C001','S001','04','04','12','20090101','20090430','50');
    INSERT INTO PAYMENTS (ELIGIBLE_MONTH, CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('01-APR-2009','C001','S001','04','04','12','20090101','20090430','50');
    INSERT INTO PAYMENTS (ELIGIBLE_MONTH, CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('01-AUG-2010','C002','S001','02','02','20','20100801','20100930','100');
    INSERT INTO PAYMENTS (ELIGIBLE_MONTH, CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('01-SEP-2010','C002','S001','02','02','20','20100801','20100930','100');

    Hi,
    788729 wrote:
    I have a table below that has START_DATE and END_DATE for each record but not individual row for each month. So, a record can have 6 months payment with start date - '20100101' to end_date 20100630.
    I need to find out payment for each month for recon.
    I want to add that month field and keep everything else exactly the same as what's in table.
    For above example it should add
    01-JAN-2010 ................................................ <--- everything else same
    01-FEB-2010 ........................
    |
    |
    |
    01-JUN-2010 ..........................................................This seems to be an easier variation of your last question:
    Re: PL/SQL LOOP MONTH
    You should have some idea about how to do it by now. Post your best attempt.
    The helpful fields are START_DATE, END_DATE, NO_OF_MONTHS1 and NO_MONTHS_2. Somethimes, NO_MONTH1 and NO_MONTHS_2 differ. Normally whe they differ, one is 00.What is the role each of those columns plays in this problem? Which one(s) tell how many rows need to be inserted? Why are the others helpful?
    >
    >
    --oracle 10g
    --DROP TABLE PAYMENTS;
    CREATE TABLE PAYMENTS
    CMPNY VARCHAR2,
    S_ID VARCHAR2,
    NO_MONTHS_1 VARCHAR2,
    NO_MONTHS_2 VARCHAR2,
    ADJ_CODE VARCHAR2,
    START_DATE VARCHAR2,
    END_DATE VARCHAR2,
    AMOUNT NUMBER
    );Don't use VARCHAR2 columns to store dates; alwyas use DATE (or TIMESTAMP) columns.
    INSERT INTO PAYMENTS (CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('C001','S001','06','06','20','20100101','20100630','30');
    INSERT INTO PAYMENTS (CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('C001','S001','04','04','12','20090101','20090430','50');
    INSERT INTO PAYMENTS (CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('C002','S001','02','02','20','20090801','20100930','100');
    INSERT INTO PAYMENTS (CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('C002','S002','02','02','20','20090801','20100930','100');
    INSERT INTO PAYMENTS (CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('C001','S002','01','01','12','20090101','20090131','50');
    INSERT INTO PAYMENTS (CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('C001','S001','00','04','18','20090101','20090430','50');
    INSERT INTO PAYMENTS (CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('C001','S003','00','02','12','20090501','20090731','50');
    INSERT INTO PAYMENTS (CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('C001','S004','01','01','12','20090101','20090131','50');
    commit;Thanks for posting the CREATE TABLE and INSERT statemnets.
    RESULTS should be something like
    CREATE TABLE PAYMENTS1
    ELIGIBLE_MONTH DATE,
    CMPNY VARCHAR2,
    S_ID VARCHAR2,
    NO_MONTHS_1 VARCHAR2,
    NO_MONTHS_2 VARCHAR2,
    ADJ_CODE VARCHAR2,
    START_DATE VARCHAR2,
    END_DATE VARCHAR2,
    AMOUNT NUMBER
    commit;
    --BELOW IS AN EXAMPLE OF HOW THE SOLUTION SHOULD COMEOUT FOR FIRST 3 RECORD IN ABOVE TABLEWhy only 3? Post the results that you want from the sample data. If 3 rows is enough to show what the problem is, why did you post 8 rows above? If 8 rows give a better picture of the problem, why not show the results from 8 rows?
    >
    ---for first record in above table, it should create 6 rows, and apply eligible_month to it
    INSERT INTO PAYMENTS (ELIGIBLE_MONTH, CMPNY,S_ID,NO_MONTHS_1,NO_MONTHS_2, START_DATE, END_DATE,AMOUNT) VALUES ('01-JAN-2010','C001','S001','06','06','20','20100101','20100630','30');There are 8 columns listed before the VALUES keyword, but 9 values given after it.
    There is no eligible_month column in paymemts. Did you mean payments<b>1</b>?
    Do you want a query that produces these INSERT statements as strings, or do you actually want to populate payments1 (or payments)?
    If you just want to populate a table, show the contents of the populated table in a form people can read and understand, for example:
    ELIGIBLE_MONTH  CMPNY  S_ID  NO_MONTHS_1  NO_MONTHS_2  START_DATE  END_DATE  AMOUNT
    01-JAN-2010     C001   S001  06            06            20100101        20100630  30
    01-FEB-2010     C001   S001  06            06            20100101        20100630  30
    ...When you post formatted text on this site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Can we assign value to a variable in PL/SQL Loop

    Hi
    Can we assign value to a variable in PL/SQL Loops?
    DECLARE
    V_Num NUMBER;
    BEGIN
    LOOP
    V_Num := 10;
    DBMS_OUTPUT.put_line(V_num);
    V_Num := V_Num - 1;
    EXIT WHEN V_Num = 0;
    END LOOP;
    END;
    In the above program, Can we assign V_num with a value 10????????
    Thanks & Regards,
    Hari Babu
    Edited by: 1004977 on Jun 5, 2013 2:40 AM

    Hi,
    1004977 wrote:
    Hi
    Can we assign value to a variable in PL/SQL Loops?
    DECLARE
    V_Num NUMBER;
    BEGIN
    LOOP
    V_Num := 10;
    DBMS_OUTPUT.put_line(V_num);
    V_Num := V_Num - 1;
    EXIT WHEN V_Num = 0;
    END LOOP;
    END;
    In the above program, Can we assign V_num with a value 10????????Yes; the example you posted does that.
    When the loop starts, the value 10 is assigned to v_num. You should see that value displayed by the put_line statement.
    After that, v_num is set to 10 - 1 = 9.
    Next, the EXIT condition is evaluated. At this point, v_num is 9, not 0, so the loop runs again. V_num is set to 10 again, and the loop continues forever (or, in some versions, until the dbms_output buffer is filled and an error occurs.)

  • PL/SQL Looping a table and copying some values to another one...

    hi all!!!
    i'm totally new to pl/sql, and i need to create an interaction to do the following..
    my scenario is:
    i have a table called "references" that contains 2 columns (new_id, old_id).
    then i have another table called "ref" which also contains 2 columns (old_id, other_id).
    ok the point is this:
    in the table references i have stored the references between 2 products (the old one and the new one) by storing their ids.
    now what i have to do by knowing this, is to insert in the table "ref" a new entry for every old_id that is already stored there, but changing it with the new_id that i can get from the other table (references).
    let's see an example:
    table references:
    new_id - old_id
    11 - 3
    12 - 7
    13 - 5
    table ref:
    old_id - other_id
    3 - tu7r
    7 - asduih
    7 - anotherone
    7 - 44444
    5 - 6754f
    so the result that i want is that the new ids (11,12,13) has to be copied to the table "ref" with the same "other_id" as their correspondants in "references" table.. the result would be:
    table ref:
    old_id - other_id
    3 - tu7r
    7 - asduih
    7 - anotherone
    7 - 44444
    5 - 6754f
    11 - tu7r
    12 - asduih
    12 - anotherone
    12 - 44444
    13 - 6754f
    i don't know how to build up a loop or something to reach this aim!!
    thanks for your time guys!!!
    Edited by: ElMazzaX on Nov 17, 2011 3:15 PM

    You do not need pl/sql to do this.
    If I understand your datamodel correctly, this join will get you those records you need to insert:
    select
    references.new_id, ref.other_id
    from references
    join ref
       on ref.old_id = references.old_id;Try that select - it it works, then you can simply do:
    insert into ref (old_id, other_id)
    select
    references.new_id, ref.other_id
    from references
    join ref
       on ref.old_id = references.old_id;SQL is quite enough - no PL/SQL loop necessary ;-)

  • Pivot sql year/month/category

    Need help with this :
    Requirement : need to pivot data based on year, month and display the sales correctly. if the data for any month does not exist that month shoudl not appear in the results.
    Sample data :
    --DROP TABLE APPS.TEST_OM_V CASCADE CONSTRAINTS;
    CREATE TABLE APPS.TEST_OM_V
    TAX_CATEGORY VARCHAR2(250 BYTE),
    SHIP_FROM_ORG_NAME VARCHAR2(100 BYTE),
    SCHEDULE_SHIP_DATE DATE,
    UNIT_SELLING_PRICE NUMBER,
    ORDERED_QUANTITY NUMBER,
    INVOICED_SALES NUMBER
    Insert into APPS.TEST_OM_V
    (TAX_CATEGORY,
    SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
    Values
    ('Operating Supplies', 'DC FONT (FONT-120)', TO_DATE('02/01/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 12, 13,
    23);
    Insert into APPS.TEST_OM_V
    (TAX_CATEGORY,
    SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
    Values
    ('COFFEE', 'DC CANADA (CAN-180)', TO_DATE('09/30/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 90, 7,
    23.34);
    Insert into APPS.TEST_OM_V
    (TAX_CATEGORY,
    SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
    Values
    ('COFFEE', 'DC Florida (FLO-180)', TO_DATE('09/14/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 30, 8,
    75);
    Insert into APPS.TEST_OM_V
    (TAX_CATEGORY,
    SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
    Values
    ('COFFEE', 'DC CANADA (CAN-180)', TO_DATE('10/30/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 30, 2,
    100.11);
    Insert into APPS.TEST_OM_V
    (TAX_CATEGORY,
    SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
    Values
    ('COFFEE', 'DC CANADA (CAN-180)', TO_DATE('08/30/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 30, 2,
    75);
    Insert into APPS.TEST_OM_V
    (TAX_CATEGORY,
    SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
    Values
    ('Operating Supplies', 'DC DIST (DIS-130)', TO_DATE('10/21/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 12, 13,
    23);
    Insert into APPS.TEST_OM_V
    (TAX_CATEGORY,
    SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
    Values
    ('COFFEE', 'DC CANADA (CAN-180)', TO_DATE('08/30/2011 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 30, 2,
    75);
    Insert into APPS.TEST_OM_V
    (TAX_CATEGORY,
    SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
    Values
    ('Operating Supplies', 'DC CANADA (CAN-180)', TO_DATE('01/02/2012 00:00:00', 'MM/DD/YYYY HH24:MI:SS'), 23, 1,
    45);
    Insert into APPS.TEST_OM_V
    (TAX_CATEGORY,
    SHIP_FROM_ORG_NAME, SCHEDULE_SHIP_DATE, UNIT_SELLING_PRICE, ORDERED_QUANTITY, INVOICED_SALES)
    Values
    ('Operating Supplies', 'DC PACK (PK-160)', NULL, 1, 2,
    1);
    COMMIT;
    Expected result , or anything close to this :
                                                                                2011                                     2012
                                                                   AUG      SEP          OCT         JAN   FEB      UNSCHEDULED
      COFFEE
                                    DC CANADA (CAN-180)          -30         606.66    -40.11         0          0          0
                                    DC Florida (FLO-180)          0           165         0           0          0          0
    Operating Supplies
                                    DC CANADA (CAN-180)           0           0            0         -22        0          0
                                    DC DIST (DIS-130)             0           0            133         0         0          0
                                    DC FONT (FONT-120)            0           0            0           0         133        0
                                    DC PACK (PK-160)              0           0            0           0          0           1 I tried grouping and summing and then lost my way...
    select TAX_CATEGORY, SHIP_FROM_ORG_NAME, nvl(TO_CHAR((SCHEDULE_SHIP_DATE), 'MM/YYYY'),'N/A') SCHEDULE_SHIP_DATE,
    sum((unit_selling_price * ORDERED_QUANTITY ) - nvl(INVOICED_SALES,0)) CARRYOVER
    from XXCNC.TEST_OM_V where 1=1
    group by TAX_CATEGORY, SHIP_FROM_ORG_NAME,nvl(TO_CHAR((SCHEDULE_SHIP_DATE), 'MM/YYYY'),'N/A')
    order by 1,2,3;
    Thanks for your help in advance.
    J

    Like this?:
    SQL> set num 6 lin 120 trims on
    SQL> col tax_category for a20
    SQL> col SHIP_FROM_ORG_NAME for a32
    SQL> break on tax_category
    SQL> SELECT *
      2  FROM (SELECT tax_category,
      3               ship_from_org_name,
      4               NVL( TO_CHAR( ( schedule_ship_date ), 'MM/YYYY' ), 'N/A' ) schedule_ship_date,
      5               ( unit_selling_price * ordered_quantity ) - NVL( invoiced_sales, 0 ) carryover
      6        FROM test_om_v) PIVOT (SUM( carryover )
      7                        FOR schedule_ship_date
      8                        IN  ('08/2011' AS "Aug'11",
      9                            '09/2011' AS "Sep'11",
    10                            '10/2011' AS "Oct'11",
    11                            '11/2011' AS "Nov'11",
    12                            '12/2011' AS "Dec'11",
    13                            '01/2012' AS "Jan'12",
    14                            '02/2012' AS "Feb'12",
    15                            'N/A' AS "UNSCHEDULED"))
    16  ORDER BY 1, 2, 3
    17  /
    TAX_CATEGORY         SHIP_FROM_ORG_NAME               Aug'11 Sep'11 Oct'11 Nov'11 Dec'11 Jan'12 Feb'12 UNSCHEDULED
    COFFEE               DC CANADA (CAN-180)                 -30 606.66 -40.11
                         DC Florida (FLO-180)                       165
    Operating Supplies   DC CANADA (CAN-180)                                                    -22
                         DC DIST (DIS-130)                                 133
                         DC FONT (FONT-120)                                                            133
                         DC PACK (PK-160)                                                                            1
    6 rows selected.:p
    Edited by: LKBrwn_DBA on Dec 16, 2011 12:18 PM

  • Problem with PL/SQL loop

    Hi,
    Here is what I am trying to do. The SQL query retrurns only one record but the loop is execuitng twice. The count returns 2. What could be the problem? Thanks for your help.
    type t_name is record(id number, c_name varchar2(100));
    type t_names is ref cursor return t_name
    Procedure returnVal()
    v_t_names t_names;
    count number;
    BEGIN
    count : = 0;
    OPEN v_t_names for select user_id, u_name from tableA WHERE dept_id = 100;
    LOOP
    FETCH v_t_names into t_name;
    Exit when v_t_names%not found;
    count := count + 1
    END LOOP
    END returnVal;
    ---------------------------------------------------------------------

    After fixing the million and one errors with your example code, I turned it into the following similar so I could run it:
    declare
      type t_name is record(id number, c_name varchar2(100));
      type t_names is ref cursor return t_name;
      v_t_names t_names;
      v_t_name_rec t_name;
      l_count number;
    BEGIN
      l_count := 0;
      OPEN v_t_names for select 1, 'Fred' from dual;
      LOOP
        FETCH v_t_names into v_t_name_rec;
        Exit when v_t_names%notfound;
        l_count := l_count + 1;
      END LOOP;
      dbms_output.put_line(l_count);
    END;
    /the output was: 1.
    The loop does get executed twice - the first time through it does a fetch, finds a record, so doesn't satisfy the EXIT criteria, and updates l_count, and finishes the first loop through. It must then go back to the top of the loop, and fetch another record. However, because there was only 1 record, the exit criteria is now met, so the procedure now jumps out of the loop without updating l_count. So, the loop has been entered twice.
    Does that explain things?
    Message was edited by:
    Boneist
    One thought: Since your code was so obviously an example you made up to illustrate your problem, can you guarentee that the "increment the counter" step was AFTER the "exit when cursor%notfound" step in the original?
    My guess is that it's before it, so that the count goes up regardless of the cursor having fetched a row or not.

  • SQL loop

    Hi Gurus
    Question :
    Using only SQL not PL/SQL* can we do loop ?
    for example :
    SELECT COUNT (*)
    FROM (SELECT object_name
    FROM all_objects
    WHERE object_type = 'TABLE')
    Now i am aware we have a static table which can give count but idea here is avoid the PL/SQL and not to use static information.
    Objective : to be able to loop using only SQL ...
    with the above mentioned query what i want to achieve is :
    1. be able to take all tables then do count on all tables one by one.
    please help provide comment

    855161 wrote:
    Again question is to challenge the intellectuals persons who can think outside the box and are creative..... thanksWhy don't you think outside the box yourself and use google or the documentation or a correct forum instead of challenge the intellectuals persons with a question that can be easily solved by taking a look at the documentation.
    take a look at the num_rows column of all_tables:
    http://docs.oracle.com/cd/E11882_01/server.112/e25513/statviews_2117.htm#i1592091
    it will be refreshed every time you gather statistics on your tables. How outside the box and creative is that for you?
    cheers

  • PL/SQL loop counter for Xpath

    I have an XML file that looks like this...
    <COL-COMPET_LNG>
    <COMPET_LNG>
    <LNG_CODE>3</LNG_CODE>
    <READ>O</READ>
    <WRITE>O</WRITE>
    <SPEAK>O</SPEAK>
    <UNDERSTAND>O</UNDERSTAND>
    </COMPET_LNG>
    <COMPET_LNG>
    <LNG_CODE>4</LNG_CODE>
    <READ>O</READ>
    <WRITE>N</WRITE>
    <SPEAK>O</SPEAK>
    <UNDERSTAND>O</UNDERSTAND>
    </COMPET_LNG>
    <COMPET_LNG>
    <LNG_CODE>1</LNG_CODE>
    <READ>O</READ>
    <WRITE>N</WRITE>
    <SPEAK>O</SPEAK>
    <UNDERSTAND>O</UNDERSTAND>
    </COMPET_LNG>
    <COMPET_LNG>
    <LNG_CODE>5</LNG_CODE>
    <READ>O</READ>
    <WRITE>N</WRITE>
    <SPEAK>O</SPEAK>
    <UNDERSTAND>O</UNDERSTAND>
    </COMPET_LNG>
    </COL-COMPET_LNG>
    Using PLSQL I would like to loop though each node and process the /LNG_CODE value. I know how to set up the loop and how to access the /LNG_CODE values for each node. I am not sure how to count the number of occurrences of each <COMPET_LNG> node so that I can use it for my max count on the loop. Can anyone help?
    Is there a good reference book I can use for this type of PL/SQL programming with XPath? I am using the Oracle manuals but I find the examples a little sparse and would love to read something with some good example code.
    Thanks
    Karen

    Chris,
    Thanks for the help. I now have a loop that works but I am not sure how to extract my data. I have tried...
    declare
    xml xmltype;
    v_other_language VARCHAR2(40);
    BEGIN
    SELECT ccv_xml INTO xml FROM ccv_xml;
    FOR i IN (SELECT value(x) FROM TABLE(XMLSEQUENCE(EXTRACT(xml,'/CV/COL-COMPET_LNG/COMPET_LNG'))) x)
    LOOP
    SELECT EXTRACTVALUE(xml,'/CV/COL-COMPET_LNG/COMPET_LNG/LNG_CODE')
    INTO v_other_language
    FROM dual
    WHERE EXTRACTVALUE(xml,'/CV/COL-COMPET_LNG/COMPET_LNG/LNG_CODE[i]') > 2;
    dbms_output.put_line('Looping'||v_other_language);
    END LOOP;
    dbms_output.put_line('END');
    END;
    But my counter 'i' does not seem to be an integer. I get the error message ORA-01403: no data found with this option. I thought I might have access to value(x) in the loop but I don't have that either. How can I access the data that I have now isolated for my loop? I am lost and I can't find an example in the Oracle XML manual.
    Thanks for your help
    Karen

  • PL/SQL Loop Issue

    Whenever a bogus item_no is in the input record the program exists the loop and doesn't process next record. I have two examples shown one with all valid item_no and processes to completion. The other with the bogus item_no and doesn't complete. I want to complete the records in the file even if the item_no doesn't exist in the mif_stg table. Your assistance is most appreciated.
    FOR no_stock_rec IN no_stock_cur
    LOOP
    DBMS_OUTPUT.PUT_LINE(no_stock_rec.item_no);
    UPDATE MIF_STG SET BALANCE_ON_HAND = 0
    WHERE MIF_STG.item_no = no_stock_rec.item_no ;
    dbms_output.put_line ('before mif status_code');
    select mif_stg.status_code into v_mif_status_code
    from mif_stg where mif_stg.item_no = no_stock_rec.item_no;
    dbms_output.put_line ('mif status_code ' || v_mif_status_code);
    END LOOP;
    R2043 481689 100327 00004
    M0675 388856 100327 00002               
    F2036 481689 100327 00005
    R0698 125034 100403 00002
    M2805 481697 100406 00001
    SQL> @C:\dataformats\sql\no-stock1.sql
    Directory created.
    Directory created.
    NO-STOCK.txt
    NO-STOCK.txt file Exists
    481689
    before mif status_code
    mif status_code 3
    388856
    before mif status_code
    mif status_code 0
    481689
    before mif status_code
    mif status_code 3
    125034
    before mif status_code
    mif status_code 7
    481697
    before mif status_code
    mif status_code
    before mif status_code
    SQLERRM: ORA-01403: no data found
    PL/SQL procedure successfully completed.
    SQL> @C:\STARPUBS\STARPUBS\dataformats\sql\no-stock1.sql
    Directory created.
    R2043 481689 100327 00004
    M0675 388856 100327 00002
    XXXXX 111111 100327 00001 bogus record ( item_no doesn't exist)               
    F2036 481689 100327 00005
    R0698 125034 100403 00002
    M2805 481697 100406 00001
    Directory created.
    NO-STOCK.txt
    NO-STOCK.txt file Exists
    481689
    before mif status_code
    mif status_code 3
    388856
    before mif status_code
    mif status_code 0
    111111
    before mif status_code
    SQLERRM: ORA-01403: no data found
    PL/SQL procedure successfully completed.

    Thanks. I'm a newbie and trying to put this together. I"m working on a process called no_stock. Here is the pseudo code thus far:
    Input NOSTOCK file: <this might not be accurate perhaps subaccount field exists>
    Accoun ITEM_ID Date QTY
    D1324 480579 100409 1
    L1277 354448 100409 1
    1.     Use the ITEM_ID in the NOSTOCK file and in the MIF table assign 0 in the BALANCE_ON_HAND field for that particular ITEM_ID.
    2.     IF the MIF.STATUS_CODE = 3 for NOSTOCK FILE ITEM_ID then INSERT RECORD to CRAM with CRAM.SUPPLYACTIONCode = ‘UR’. –UR UNDER REVISON
    3.     ELSE IF MIF.STATUS_CODE = 4 for NOSTOCK FILE ITEM_ID then INSERT RECORD to CRAM with CRAM.SUPPLYACTIONCode = ‘NR’. -- NOT REPRINT
    4.     ELSE IF MIF.STATUS_CODE = 8 for NOSTOCK.ITEM_ID then
    <program stub> POD processing………. To be continued at a later time.
    --Not status code 3, 4 or 8
    5.     ELSE NOSTOCK.ITEM_ID = MIF.ITEM_ID then UPDATE MIF
    MIF.BACKORDER + NOSTOCK.QTY -- add qty to backorder qty
    INSERT NOSTOCK RECORD to DUE_OUT
    UPDATE CRAM.SUPPLYACTIONCODE = ‘DO’ for NOSTOCK.ITEM_ID.
    Resources involve:
    Input NOSTOCK file
    MIF Table
    CRAM table
    DUE_OUT Table.
    Here is my current program:
    set serveroutput on
    create or replace directory user_dir as 'c:\dataformats\incoming\';
    create or replace directory history_dir as 'c:\dataformats\history\';
    DECLARE
    v_filename VARCHAR2(100); -- Data filename
    v_file_exists boolean;
    v_file_length number;
    v_block_size number;
    f utl_file.file_type;
    no_stock_rec ext_no_stock_table%rowtype;
    v_mif_status_code mif_stg.status_code%TYPE;
    CURSOR no_stock_cur IS
    SELECT * from ext_no_stock_table;
    BEGIN
    v_filename := 'NO-STOCK.txt';
    DBMS_OUTPUT.PUT_LINE(v_filename); --shows filename
    utl_file.fgetattr('USER_DIR', v_filename, v_file_exists, v_file_length ,v_block_size );
    IF v_file_exists THEN
    dbms_output.put_line( 'NO-STOCK.txt file Exists');
    FOR no_stock_rec IN no_stock_cur
    LOOP
    DBMS_OUTPUT.PUT_LINE(no_stock_rec.item_no);
    UPDATE MIF_STG SET BALANCE_ON_HAND = 0
    WHERE MIF_STG.item_no = no_stock_rec.item_no ;
    dbms_output.put_line ('before mif status_code');
    select mif_stg.status_code into v_mif_status_code
    from mif_stg where mif_stg.item_no = no_stock_rec.item_no;
    dbms_output.put_line ('mif status_code ' || v_mif_status_code);
    END LOOP;
    commit;
    /* utl_file.frename('USER_DIR', v_filename, 'HISTORY_DIR', v_filename || '_' || to_char(SYSDATE,'ddMonth'),
    TRUE);
    ELSE
    dbms_output.put_line('File Does Not Exist');
    END IF; -- file exists
    EXCEPTION
    WHEN UTL_FILE.ACCESS_DENIED THEN
    DBMS_OUTPUT.PUT_LINE('No Access!!!');
    WHEN UTL_FILE.INVALID_PATH THEN
    DBMS_OUTPUT.PUT_LINE('PATH DOES NOT EXIST');
    WHEN others THEN
    DBMS_OUTPUT.PUT_LINE('SQLERRM: ' || SQLERRM);
    END;
    /

  • PL/SQL loop

    Hi Guys,
    Need help here as I'm not good with PL\SQL.
    Coming out with a script to purge recycle_bin objects that is older than 14 days.
    Basically the syntax will be : purge table owner.object_name.
    Please see below:
    Can help to correct? I think shouldn't be
    --Purge table
    sql_stmt := 'PURGE TABLE i.owner."i.object_name"';
    EXECUTE IMMEDIATE sql_stmt;
    thanks!
    create or replace
    PROCEDURE PURGE_RECYCLEBIN
    AS
    sql_stmt VARCHAR2(200);
    CURSOR LIST_TO_DELETE IS
    Select owner,OBJECT_NAME,TYPE, droptime
    from dba_recyclebin
    Where to_char(to_date(droptime, 'rrrr-mm-dd hh24:mi:ss'), 'dd-mm-rrrr') < to_char(Sysdate, 'dd-mm-rrrr')
    and type='TABLE'
    order by droptime;
    BEGIN
    --Loop through list of tables to purge
    FOR i in LIST_TO_DELETE LOOP
    BEGIN
    --Purge table
    sql_stmt := 'PURGE TABLE i.owner."i.object_name"';
    EXECUTE IMMEDIATE sql_stmt;
    --Rollback all if got any errors.
    EXCEPTION WHEN OTHERS THEN
    ROLLBACK;
    END;
    END LOOP;
    COMMIT;
    END PURGE_RECYCLEBIN;
    /

    dbaing wrote:
    Need help here as I'm not good with PL\SQL.The main thing is being "good" at programming - i.e. understanding concepts like structured programming, exception management, modularisation and so on. This is true in all programming languages. And if you get these basics right, you will be able to right good code in any programming language.
    When executing that SQL statement - what do you when it fails? For example, the purge command can fail for some or other reason. Do you continue with the loop? Do you halt processing?
    You can modularise that and create a procedure whose sole task is to execute a dynamic SQL statement and deal with exceptions that may occur.
    E.g. the procedure can be instructed to ignore dynamic SQL exceptions - if that is a requirement.
    create or replace procedure ExecSQL( dynamicSQL varchar2, ignoreError boolean default false ) is
    begin
      execute immediate dynamicSQL;
    exception when OTHERS then
      if not ignoreError then
        raise;
      end if;
    end;Instead of stringing literals and variables together to make up a dynamic SQL statement, it is far easier to maintain a "template". And then simply substitute tokens/variables in this template with values. E.g.
    create or replace procedure PurgeRecyclebin is
       PURGE_TEMPLATE constant varchar2(1000) := 'purge table "$OWNER"."$TABLE"';
       purgeSQL varchar2(1000);
    begin
      for c in (select ... ) loop
        purgeSQL := replace( PURGE_TEMPLATE, '$OWNER', c.owner );
        purgeSQL := replace( purgeSQL, '$TABLE', c.table_name );
        ExecSQL( dynamicSQL => purgeSQL, ignoreError => true );
      end loop;
    end;Instrumentation is another basic concept for good programming. These examples are not instrumented - but should be. For example, recording the actual dynamic SQL statement executed and the SQL%Code response for that execution. Or the duration of the dynamic SQL execution. Etc.
    The bottom line is that good programming starts with getting the fundamentals of software engineering right - it is not only about how good your knowledge of that particular programming language is.

  • PL/SQL Loop is too slow??

    Hi all,
    I have a basic loop (LOOP..END LOOP) for reading a very large varchar2 variable. In this Loop i always read 1 caracter for header (size in bytes) and the amount of data. Why this loop processing is too slow??? Can i boost it with something?
    Thanx.

    Function to read data on a socket
    Always read 1 byte for length, and with this length,
    body of message.
    FUNCTION PEGA_MESG (io_Conex_Env IN OUT Utl_Tcp.connection)
    RETURN LONG RAW
    IS
    v_Buffer LONG RAW;
    v_Mesg LONG RAW;
    v_intResp INTEGER;
    v_intBytes INTEGER;
    v_qtde_bytes integer;
    BEGIN
    v_Mesg := NULL;
    LOOP
    v_intResp := utl_tcp.read_raw(io_Conex_Env, v_Buffer, 1);
    v_qtde_bytes := ascii(utl_raw.cast_to_varchar2(v_Buffer));
    v_intResp := utl_tcp.read_raw(io_Conex_Env, v_Mesg, v_qtde_bytes);
    EXIT WHEN v_Mesg is not null;
    END LOOP;
    RETURN(v_Mesg);
    END;
    This is a little peace of my prog. If i send a lot of data, my prog get too slow.
    loop
    v_Mesg := Pega_Mesg(io_conexao);
    if ( v_Mesg = utl_raw.cast_to_raw('sum')) then
    v_Mesg := Pega_Mesg(io_conexao);
    l_Dados.DELETE;
    while v_Mesg <> utl_raw.cast_to_raw('fimsum') loop
    for sumario in 1..4 loop -- Loop para quantidade de campos na tabela saida_sumario
    l_Dados(sumario) :=Long postings are being truncated to ~1 kB at this time.

  • SQL Query Month Insertion

    Hi,
    I have a table with data below:
    YEAR MONTH DIRECTION CHANNEL_ID COUNT_CURR_YR
    2005 8 A CD 27
    2005 10 A CD 37
    2005 11 A CD 42
    2005 12 A CD 41
    2006 1 A CD 38
    2006 2 A CD 36
    2006 3 A CD 38
    2006 4 A CD 52
    2006 5 A CD 49
    2006 6 A CD 39
    2006 7 A CD 40
    2006 8 A CD 45
    2006 9 A CD 41
    2006 10 A CD 41
    2006 11 A CD 49
    2006 12 A CD 34
    2007 1 A CD 33
    2007 2 A CD 29
    2007 3 A CD 37
    2007 4 A CD 32
    2007 5 A CD 37
    2007 6 A CD 33
    2007 7 A CD 36
    2007 8 A CD 37
    2007 9 A CD 45
    2007 10 A CD 36
    2007 11 A CD 31
    2007 12 A CD 34
    2008 1 A CD 34
    2008 2 A CD 36
    2008 3 A CD 44
    2008 6 A CD 35
    2008 7 A CD 28
    2008 8 A CD 34
    2009 12 A CD 5
    2005 8 A CH 138
    2005 9 A CH 1
    2005 10 A CH 152
    2005 11 A CH 138
    2005 12 A CH 136
    2006 1 A CH 137
    2006 2 A CH 125
    2006 3 A CH 135
    2006 4 A CH 132
    2006 5 A CH 136
    2006 6 A CH 144
    2006 7 A CH 144
    2006 8 A CH 142
    2006 9 A CH 129
    2006 10 A CH 126
    2006 11 A CH 117
    2006 12 A CH 129
    2007 1 A CH 120
    2007 2 A CH 113
    2007 3 A CH 134
    2007 4 A CH 144
    2007 5 A CH 135
    2007 6 A CH 147
    2007 7 A CH 136
    2007 8 A CH 135
    2007 9 A CH 135
    2007 10 A CH 143
    2007 11 A CH 143
    2007 12 A CH 139
    2008 1 A CH 118
    2008 2 A CH 129
    2008 3 A CH 134
    2008 6 A CH 130
    2008 7 A CH 140
    2008 8 A CH 143
    2009 12 A CH 22
    71 rows selected
    I want two things to be done:
    1.Insert Rows for the months for which I do not have any data with 0 Values Example:
    YEAR MONTH DIRECTION CHANNEL_ID COUNT_CURR_YR
    2005 8 A CD 27
    2005 1 A CD 0
    2005 2 A CD 0
    2005 12 A CD 41
    Also I want another column added to this which will give me results for last year same month.
    Example:
    YEAR MONTH DIRECTION CHANNEL_ID COUNT_CURR_YR PREVIOUS_YR
    2005 8 A CD 27 <Count of 8/2004>
    2005 1 A CD 0 <Count of 1/2004>
    2005 2 A CD 0 <Count of 2/2004>
    2005 12 A CD 41 <Count of 12/2004>
    The script to create table and insert dummy data is below:
    CREATE TABLE TESTING_123
    (YEAR NUMBER,
    MONTH NUMBER,
    DIRECTION VARCHAR2(1),
    CHANNEL_ID VARCHAR2(2),
    COUNT_CURR_YR NUMBER);
    INSERT INTO TESTING_123 VALUES(2005,8,'A','CD',27);
    INSERT INTO TESTING_123 VALUES(2005,10,'A','CD',37);
    INSERT INTO TESTING_123 VALUES(2005,11,'A','CD',42);
    INSERT INTO TESTING_123 VALUES(2005,12,'A','CD',41);
    INSERT INTO TESTING_123 VALUES(2006,1,'A','CD',38);
    INSERT INTO TESTING_123 VALUES(2005,8,'A','CH',138);
    INSERT INTO TESTING_123 VALUES(2005,9,'A','CH',1);
    INSERT INTO TESTING_123 VALUES(2005,10,'A','CH',152);
    Let me know if you need any other info and thanks in advance for your help.
    Edited by: 884073 on Sep 8, 2011 10:09 AM

    Hi,
    Welcome to the forum!
    Thanks for posting the CREATE TABLE and INSERT statements, that's very helpful.
    Don't forget to post the results you want from that data.
    Explain how you get the results you want from the data given. For example, what role do direction and channel_id play in this problem? What should be the earliest and latest dates in the output?
    Do you actually want to add new rows to the table, or do you just want the rows for missing months to appear in the output? I'm guessing that you only want them in the output. If you want to change the table, you can use soemthing like sub-query all_months in a MERGE statement.
    WITH   got_year_month     AS
         SELECT     year, month, direction, channel_id, count_curr_yr
         ,     TO_DATE ( TO_CHAR (year) || TO_CHAR (MONTH, '00')
                   , 'YYYY MM'
                   )          AS year_month
         FROM    testing_123
    --     WHERE     ...     -- if you need any filtering, put it here
    ,     all_year_months     AS
         SELECT     ADD_MONTHS ( start_year_month
                      , LEVEL - 1
                      )          AS year_month
         FROM    (
                  SELECT  MIN (year_month)     AS start_year_month
                  ,          MAX (year_month)     AS end_year_month
                  FROM    got_year_month
         CONNECT BY     LEVEL <= 1 + MONTHS_BETWEEN (end_year_month, start_year_month)
    SELECT       TO_CHAR (a.year_month, 'YYYY')     AS year
    ,       TO_CHAR (a.year_month, 'fmMM')     AS month
    ,       g.direction
    ,       g.channel_id
    ,       NVL ( g.count_curr_yr
               , 0
               )                         AS count_curr_yr
    ,       LAG ( NVL ( g.count_curr_yr
                        , 0
               , 3     -- 3 for testing, 12 for real
               )     OVER ( PARTITION BY  g.direction
                           ,          g.channel_id
                     ORDER BY          a.year_month
                   )                    AS previous_yr
    FROM           all_year_months  a
    LEFT OUTER JOIN  got_year_month       g  PARTITION BY (direction, channel_id)
                                      ON  a.year_month     = g.year_month
    ORDER BY  direction
    ,            channel_id
    ,       a.year_month
    ;Storing date information in NUMBER columns is a really bad idea. Think about using a DATE column, instead. If you must use two NUMBER columns, start the query by generating a DATE from them, as I didin the first sub-query, got_year_month.
    Output:
    YEAR MO D CH COUNT_CURR_YR PREVIOUS_YR
    2005 8  A CD            27
    2005 9  A CD             0
    2005 10 A CD            37
    2005 11 A CD            42          27
    2005 12 A CD            41           0
    2006 1  A CD            38          37
    2005 8  A CH           138
    2005 9  A CH             1
    2005 10 A CH           152
    2005 11 A CH             0         138
    2005 12 A CH             0           1
    2006 1  A CH             0         152Your sample data only covered a span of 6 months, so the previous_yr column should always be NULL. (If you want 0, then use "NVL (LAG ...)" where I used "LAG (NVL ..)" above.) To show how it works, I'm sjhowing the data from 3 months ago in the previous_yr column. You'll want to change the hard-coded 3 to 12.
    Always say which version of Oracle you're using. This query will work in Oracle 10.1 (and higher).

  • PL/SQL Loop without stopping

    Hi, I have a list of procedure name in PROCLIST table. I am planning to fetch it and interate using loop. Inside loop I have to execute the same name procedure.
    Problem : The procedure I have to execute without stopping means in the 1st iteration execute 1st procedure, before completion of the 1st procedure it should iterate for next and execute the 2nd procedure. so my task is to execute this all the procedures parallely. Any type of help is appreciated.

    Hi,
    Thanks for reply. I have tried with the same package. but my all the procedure's name in table which I am fetching using cursor loop.
    My task is to fetch procedure name from the loop and executed it but the loop shouldn't wait for the 1st procedure to complete. Without waiting for 1st procedure to complete, it should interate for the next & fetch the 2nd procedure's name and execute 2nd procedure parallely.

  • Calculating given occurance of a given day in every month

    Hi,
    I'm using oracle 10.2.0.1.0 and forms 6i.
    I have inputs like frequency, day and start date.
    Suppose
    Start Date : 12-03-2011
    Day : Saturday
    Frequency : 2
    What i want to do is, i want to calculate 2nd occurance of saturday(2nd Saturday), in every month, starting from the given date, till the end of the year.
    The given start date, is anyway the 2nd occurance of saturday in March.
    So now in april -- its is 09-04-2011
    May -- 14-05-2011
    June -- 11-06-2011
    Is there a way to calculate like this?
    Please help
    Thanks

    Hi,
    Another way is to use the NEXT_DAY function, like this:
    WITH     parameters     AS
         SELECT     DATE '2011-03-12'     AS start_date
         ,     'SATURDAY'          AS week_day
         ,     2               AS week_num     -- This isn't really a frequency
         FROM     dual
    ,     all_dates     AS
         SELECT  start_date
         ,     NEXT_DAY ( ADD_MONTHS ( TRUNC (start_date, 'MONTH')
                              , LEVEL - 1
                              ) + (7 * week_num)
                             - 8
                     , week_day
                    )     AS a_date
         FROM     parameters
         CONNECT BY     LEVEL     <= 12
    SELECT       a_date
    FROM       all_dates
    WHERE       a_date          >= start_date
    AND       TRUNC (a_date, 'YEAR') = TRUNC (start_date, 'YEAR')
    ORDER BY  a_date
    ;If you're doing this in Oracle Forms, then you don't need a sub-query like parameters. You can pass the parameters in PL/SQL variables, and use dual as the base table in all_dates (or use a PL/SQL loop).
    The calculation of a_date works like this:
    First, we find the beginning of the month.
    Then, we add wekk_num weeks to that. For example, if week_num=2, that will give us the beginning of the 3rd week.
    We're interested in the week before that, so we subtract 7, and we also subtract another 1 because NEXT_DAY always returns a date after (not the same as) its 1st argument.
    Unfortunately, NEXT_DAY is always dependent on NLS_LANGUAGE. If you specify 'Saturday', but that day is called 'Lördag' in your NLS language, you'll get an error. If that's a possibility, then you can change the first sub-query like this:
    WITH     parameters     AS
         SELECT     DATE '2011-03-12'     AS start_date
         ,     TO_CHAR ( DATE '2011-04-02'     -- or any Saturday
                   , 'DAY'          
                   )          AS week_day
         ,     2               AS week_num
         FROM     dual
    ) ...Instead of April 2, 2011, you can you any Saturday you want; just be sure it's a Saturday.

  • Calculate the current  fiscal quarter based on zero based month index

    Hi All,
    I need your help to Calculate the current fiscal quarter by adding 1 to a 0 based month index, dividing by 3.0(float or double) and getting the ceiling integer then add one to that number to get the “fiscal” quarter, taking care to loop back to quarter one as necessary.
    please help me to get this.
    Thank you in Advance.
    Ram.

    Hi,
    933478 wrote:
    I need your help to Calculate the current fiscal quarter
    The Q datetime format doesn't match your need ?Scott@my11g SQL>select sysdate, to_char(sysdate,'Q') currentQuarter from dual;
    SYSDATE             CURRENTQUARTER
    10/05/2012 17:35:02 2If your input is the 0-based month, then you could just :Scott@my11g SQL>with monthes as (
      2  select level-1 mon0 from dual connect by level <=12
      3  )
      4  select mon0, to_char(to_date(mon0+1,'mm'),'Q') quarter from monthes;
          MON0 QUARTER
             0 1
             1 1
             2 1
             3 2
             4 2
             5 2
             6 3
             7 3
             8 3
             9 4
            10 4
            11 4

Maybe you are looking for

  • Do I need a license?

    I got into a discussion recently about licensing issues and was told that even though we bought the Flash software to develop swf files we still need to purchase a license to use flash content on a web site, I never heard of this and disagreed with t

  • Is this possible through sql loader

    hi grus, i want to load a data through sql loader but the problem is, data file contains some numeric values and after each numeric value there is sign character, for example position 1 to 9 = 12345678- (in case of negative) or position 1 to 9 = 1234

  • Which Tiger update version is the best?

    Have installed the original Tiger 10.4 on my Sawtooth 400mHz. Need to do a software update, but not sure which of the updates (from 10.4.1 to 10.4.11) is the best one to use without having any headaches. I have not installed any other software on the

  • Internet Cards for the Mac

    I am wondering, does Apple manufacture Internet cards for the Mac? If the answer is no, which third-party-companies manufacture Internet cards that are compatible with the Mac? Which of those Internet cards are the best?

  • Disabling ALT+CTRL+Del keys

    Hi Every body: Can u please help me in disabling the end task for my swing application by disabling the ALT+CTRL+Del keys ..I'm not sure if that is possible in Java ... Thanx in advance