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).

Similar Messages

  • SQL Query for insertion

    hi
    I got two tables
    BOOK (DDC,TITLE,ISBN,AUTH_NAME)
    AUTHOR (DDC,AUTH_NAME)
    Table "BOOK" contains about 50000 records but its
    AUTH_NAME column contains NULL for all 50000 records.
    I want insert AUTH_NAME column's values from AUTHOR table
    into BOOK's AUTH_NAME column where DDC number match.
    Please write me the query for it.
    thanks

    hi,
    AUTH_NAME column contains NULL for all 50000 records.
    I want insert AUTH_NAME column's values from AUTHOR table
    into BOOK's AUTH_NAME column where DDC number match.As u mentioned above auth_name contains null value, so instead of updatring u can directly insert the records from book table.
    And what are you updating as it contains no data(i.e null value)
    Regards
    Jafar

  • Need to send success or failure message to BAPI of SQL query action block

    Hi All,
    I need to send success or failure message(i.e. 1 or 0) to BAPI which has been called below sql query action block in transaction
    Here in SAP, i have created on BAPI with one import parameter and one export parameter.
    In the sql query action block, it insert records in the database table. If it fail or success, that message(numeric value 1 or 0) has to send to SAP program through BAPI.
    I have created a SAP ABAP program which sends message to MII Message listener through RFC then in the process rule message it will call transaction, in transaction, sql query will insert records into database table.  if it success or fail, it will pass to BAPI. And i calling that BAPI in the same SAP ABAP Program to show in the output screen.
    Here the issues, i am not getting the value from BAPI which has send by the transaction in MII.
    SAP Jco, I have mapped in conf. links --> BAPI input with sql query sucess
    Thanks,
    Kind Regards,
    Praveen Reddy M

    Dear All,
    I am facing problem regarding completion notifications in Oraclr r12, when user click the upon completion generated notifications it can only be viewd once, second time user cannot view the notifications.
    I have find that fnd_file_temp table store this information and deleted it.
    Plz help me how to view this URL again.
    thanks
    regards,
    Zubyr

  • Sql Query to store record like warehoue wise items

    Hi Experts
    I want to ask you a sql query for inserting records from two table OITM and OWHS in a user definded table like OITW.
    I have a table BINMASTER in which bin code are stored. Now I want to create a table Like OWHS where BIN Wise Item records to be stored Let See
    Item01 Bin 01
    Item02 Bin 01
    Item03 Bin 01
    Item01 Bin 02
    Item02 Bin 02
    Item03 Bin 02
    Plz give your suggestions
    Regards
    Gorge

    hi János Nagy 
    Thank for reply
    your statement is fine with no where condition. But I want to insert in a UDT in which Code, Name are two field which should be unique for every record. I use following statement
    Insert into (Code, name, Itemcode, ItemDescription, Bincode , Warehouse )
    select                                      ?,     ?, T1.Itemcode, T2.ItemDescription, T2.Bincode , T3.WhsCode From Oitm T1, T2, Owhs T3
    Here what I insert in Code and Name fields
    Regards
    Gorge

  • 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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Get a insert session value for SQL query at report

    Hi friends
    I created a global temp table and procedure to support web search form.
    and a search result report. The procudure
    gets search result from multip tables and
    insert into temp table --recordsearch. I can get value from temp table  by call procedure
    at SQL*Plus.
    However, I can not get this value by web report.
    How can I get this insert session value and pass to SQL query for report?
    Thanks,
    Newweb
    CREATE GLOBAL TEMPORARY TABLE recordsearch
    (emp_id          VARCHAR2(200),
    ssn               VARCHAR2(9),
    fname          VARCHAR2(200),
    lname           VARCHAR2(200),
    m_name          VARCHAR2(200)
    ) ON COMMIT PRESERVE ROWS;

    it possible that your web form does not have a persistent, dedicated connection. if you have connection pooling for example, multiple sessions will see the same instance of the GTT, so if one deletes it, then nobody sees it (or you can see others data). if the connections are not persistent, then they can disconnect between calls, deleting the GTT table.

  • SQL Query produces different results when inserting into a table

    I have an SQL query which produces different results when run as a simple query to when it is run as an INSERT INTO table SELECT ...
    The query is:
    SELECT   mhldr.account_number
    ,        NVL(MAX(DECODE(ap.party_sysid, mhldr.party_sysid,ap.empcat_code,NULL)),'UNKNWN') main_borrower_status
    ,        COUNT(1) num_apps
    FROM     app_parties ap
    SELECT   accsta.account_number
    ,        actply.party_sysid
    ,        RANK() OVER (PARTITION BY actply.table_sysid, actply.loanac_latype_code ORDER BY start_date, SYSID) ranking
    FROM     activity_players actply
    ,        account_status accsta
    WHERE    1 = 1
    AND      actply.table_id (+) = 'ACCGRP'
    AND      actply.acttyp_code (+) = 'MHLDRM'
    AND      NVL(actply.loanac_latype_code (+),TO_NUMBER(SUBSTR(accsta.account_number,9,2))) = TO_NUMBER(SUBSTR(accsta.account_number,9,2))
    AND      actply.table_sysid (+) = TO_NUMBER(SUBSTR(accsta.account_number,1,8))
    ) mhldr
    WHERE    1 = 1
    AND      ap.lenapp_account_number (+) = TO_NUMBER(SUBSTR(mhldr.account_number,1,8))
    GROUP BY mhldr.account_number;      The INSERT INTO code:
    TRUNCATE TABLE applicant_summary;
    INSERT /*+ APPEND */
    INTO     applicant_summary
    (  account_number
    ,  main_borrower_status
    ,  num_apps
    SELECT   mhldr.account_number
    ,        NVL(MAX(DECODE(ap.party_sysid, mhldr.party_sysid,ap.empcat_code,NULL)),'UNKNWN') main_borrower_status
    ,        COUNT(1) num_apps
    FROM     app_parties ap
    SELECT   accsta.account_number
    ,        actply.party_sysid
    ,        RANK() OVER (PARTITION BY actply.table_sysid, actply.loanac_latype_code ORDER BY start_date, SYSID) ranking
    FROM     activity_players actply
    ,        account_status accsta
    WHERE    1 = 1
    AND      actply.table_id (+) = 'ACCGRP'
    AND      actply.acttyp_code (+) = 'MHLDRM'
    AND      NVL(actply.loanac_latype_code (+),TO_NUMBER(SUBSTR(accsta.account_number,9,2))) = TO_NUMBER(SUBSTR(accsta.account_number,9,2))
    AND      actply.table_sysid (+) = TO_NUMBER(SUBSTR(accsta.account_number,1,8))
    ) mhldr
    WHERE    1 = 1
    AND      ap.lenapp_account_number (+) = TO_NUMBER(SUBSTR(mhldr.account_number,1,8))
    GROUP BY mhldr.account_number;      When run as a query, this code consistently returns 2 for the num_apps field (for a certain group of accounts), but when run as an INSERT INTO command, the num_apps field is logged as 1. I have secured the tables used within the query to ensure that nothing is changing the data in the underlying tables.
    If I run the query as a cursor for loop with an insert into the applicant_summary table within the loop, I get the same results in the table as I get when I run as a stand alone query.
    I would appreciate any suggestions for what could be causing this odd behaviour.
    Cheers,
    Steve
    Oracle database details:
    Oracle Database 10g Release 10.2.0.2.0 - Production
    PL/SQL Release 10.2.0.2.0 - Production
    CORE 10.2.0.2.0 Production
    TNS for 32-bit Windows: Version 10.2.0.2.0 - Production
    NLSRTL Version 10.2.0.2.0 - Production
    Edited by: stevensutcliffe on Oct 10, 2008 5:26 AM
    Edited by: stevensutcliffe on Oct 10, 2008 5:27 AM

    stevensutcliffe wrote:
    Yes, using COUNT(*) gives the same result as COUNT(1).
    I have found another example of this kind of behaviour:
    Running the following INSERT statements produce different values for the total_amount_invested and num_records fields. It appears that adding the additional aggregation (MAX(amount_invested)) is causing problems with the other aggregated values.
    Again, I have ensured that the source data and destination tables are not being accessed / changed by any other processes or users. Is this potentially a bug in Oracle?Just as a side note, these are not INSERT statements but CTAS statements.
    The only non-bug explanation for this behaviour would be a potential query rewrite happening only under particular circumstances (but not always) in the lower integrity modes "trusted" or "stale_tolerated". So if you're not aware of any corresponding materialized views, your QUERY_REWRITE_INTEGRITY parameter is set to the default of "enforced" and your explain plan doesn't show any "MAT_VIEW REWRITE ACCESS" lines, I would consider this as a bug.
    Since you're running on 10.2.0.2 it's not unlikely that you hit one of the various "wrong result" bugs that exist(ed) in Oracle. I'm aware of a particular one I've hit in 10.2.0.2 when performing a parallel NESTED LOOP ANTI operation which returned wrong results, but only in parallel execution. Serial execution was showing the correct results.
    If you're performing parallel ddl/dml/query operations, try to do the same in serial execution to check if it is related to the parallel feature.
    You could also test if omitting the "APPEND" hint changes anything but still these are just workarounds for a buggy behaviour.
    I suggest to consider installing the latest patch set 10.2.0.4 but this requires thorough testing because there were (more or less) subtle changes/bugs introduced with [10.2.0.3|http://oracle-randolf.blogspot.com/2008/02/nasty-bug-introduced-with-patch-set.html] and [10.2.0.4|http://oracle-randolf.blogspot.com/2008/04/overview-of-new-and-changed-features-in.html].
    You could also open a SR with Oracle and clarify if there is already a one-off patch available for your 10.2.0.2 platform release. If not it's quite unlikely that you are going to get a backport for 10.2.0.2.
    Regards,
    Randolf
    Oracle related stuff blog:
    http://oracle-randolf.blogspot.com/
    SQLTools++ for Oracle (Open source Oracle GUI for Windows):
    http://www.sqltools-plusplus.org:7676/
    http://sourceforge.net/projects/sqlt-pp/

  • Need help in SQL Query: Update a row in a table & insert the same row into another table

    I want to update a row in a table say Table A and the updated row should be inserted into another table say Table B. I need to do it in a single SQL query and i don't want to do it in PL/SQL with triggers. And i tried with MERGE statement but its working with this scenario. (Note: I'm using Oracle Database 10g Enterprise Edition Release 10.2.0.1.0).
    Thanks in Advance.

    Using Sven's code as an example, you could save the updated row in a sql plus variable. (also untested):
    SQL> var v_id number
    update tableA  
    set colB='ABC' 
    where colC='XYZ' 
    returning id into :v_id;
    insert into table A_History (ID, colA, colB, ColC)  
    select id, ColA, ColB, ColC  
    from tableA  
    where id = :v_id;   

  • Build a sql query fro different table and insert into a table

    Hi I have a requirement ,
    i have some table 1 table which holds rules which rules i have to apply on the sql query
    2 table will hold table name and column name and transformation
    with these help of 2 tables i want to build a sql quey and the sql query need to be insert into another  table.

    Hi Karthick,
    I am not going to build Dynamic Data Model.
    i already have table 1 contains rules let's say COUNT,
    and another table contain source table name , column name , Target table name, Source Table name like that
    so with the help of these 2 tables i want to build Sql query and going to insert into 3rd table.

  • How to build an SQL Query to print Week ranges of a Month

    Hi Gurus!!
    I have a requirement to create a query to display the Week periods of a month.
    The inputs will be Year and month.
    The result should be some thing like this:
    If Year = 2009 and Month = June
    The SQL Query should return the following:
    01-Jun-2009 to 06-Jun-2009
    07-Jun-2009 to 13-Jun-2009
    14-Jun-2009 to 20-Jun-2009
    21-Jun-2009 to 27-Jun-2009
    27-Jun-2009 to 30-Jun-2009
    I am confused how to do this. Please help me. Any help would be grately Appreciated.
    Thanks
    Ahmed

    This is how My Final Query Looks Like:
    SELECT TO_CHAR(SYSDATE+7*(level-1),'DD-MON-RRRR')
    ||' to '
    ||TO_CHAR(SYSDATE+7*(level-1)+6,'DD-MON-RRRR') RANGES
    FROM dual
    connect by level<=5
    --Ahmed                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • I want to use the SQL query IF EXIST to update or insert data in a ms access table, but it doesn´t work

    Hi,
    I want to use the SQL query IF EXIST to update or insert data in a ms access table, but it doesn´t work
    (fault number -2147217900)
    I want to search for a value in a ms access table , if it exist i want to update it, if not i want to insert a new row.
    Working with LabView 7.1, database con. toolset.
    Who can HELP?
    Thanks a lot
    Marco

    Hello,
    I think that If exist is not a standar SQL command (I know it exists I think in Oracle and SQL server), MS access doesn't support it, so I think the best way to do it is first make a Select and then either an Update or an insert, sorry...
    Paulo

  • How to insert the records using sql query

    hi,
    i insert the record uisng sql query and DOTNET programme successfully and increase the doc num .ubut when i try to  add record using SAP B1 the old Doc no show.It means its not consider the docnums which are not inserted by sql query.
    how can i solve this problem?
    Regards,
    M.Thippa Reddy

    You are not support use Insert / Update / Delete on SAP Databases directly.
    SAP will not support any database, which is inconsistent, due to SQL-Queries, which modify datasets or the datastructure of the SAP Business One Database. This includes any update-, delete- or drop-statements executed via SQL-Server Tools or via the the query interface of SAP Business One
    Check SAP Note: 896891 Support Scope for SAP Business One - DB Integrity
    [https://websmp130.sap-ag.de/sap(bD1lbiZjPTAwMQ==)/bc/bsp/spn/smb_searchnotes/display.htm?note_langu=E&note_numm=896891]

  • Using SQL Query for page item source does not insert populated value

    Hi All,
    Following are the attribute details of a certain page item on an edit form:
    Display As: Text Field
    Page Item Source Type: SQL Query
    Source value Expression: SELECT a from tab where id = 'ABC'
    Although the field appears populated on the screen, but the value is not inserted in the table.
    Can anyone help on this?
    Thanks in advance,
    Annie

    Annie:
    One solution is to define a pl/sql function that given a date will return the 'run-date'. Something like create or replace function get_prod_date(p_date in date) return date is
    retval date;
    begin
    select run_date into retval from tab_x where run_date=p_date;
    return retval;
    end;Change the Source Type for the page-item back to 'Database Column'
    Set Source value or expression to the 'database column name'
    Set 'Post calculation computation' to be
    get_prod_date(:pxx_date)
    Varad

  • SQL query to get last 6 months records neglect the current month

    Hi All;
    I need help with 
    sql query to get last 6 months records neglect the current month
    Any help much appreciated
    Thanks
    Pradnya07

    SELECT <> FROM tbl WHERE dt >=dateadd(month,-6,GETDATE())
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • QUERY FOR INSERT INTO  SQL TABLE

    Hi all,
    i want to insert some records into SQL table but not SAP database table. This table is only present in SQL database &
    not present in SAP database.
      i want to write a program in SAP to update the SQL table(not present in SAP database). is it possible?
       if yes, plz give me the query for inserting records into SQL table.
    Regards

    Hello,
    working on the same issue:
    Try this:
    DATA : Begin Of XY Occurs 1000,
            id(15)    TYPE C,
            Name(50)  TYPE C,
            ArtNr(50) TYPE C,
            lieferant TYPE I,
         End Of XY.
    Fill this internal Table with the SAP-Table
    START Connection to your Database
      EXEC SQL.
          Connect TO 'TEST_FH'
      ENDEXEC.
      IF SY-SUBRC EQ 0.
        EXEC SQL.
        Set Connection 'TEST_FH'     " <-- this is defines with TCode dbco
        ENDEXEC.
        IF SY-SUBRC EQ 0.
        Else.
          " OUT_Msg = '... won't connect'.
          Exit.
        EndIf.  " Else IF SY-SUBRC EQ 0
      Else.
        " OUT_Msg =  'Error at Set Connection Test_FH'.
        Exit.
      EndIf.  " IF SY-SUBRC EQ 0
    ENDE  Connection to your Database
    START Insert your table XY to an external database
        Loop AT XY.
          Try.
           EXEC SQL.
               INSERT INTO stoff
               (id, name , artnr, lieferant)
               VALUES
               ( :XY-ID,  :XY-Name, :XY-ArtNr, :XY-Lieferant )
           ENDEXEC.
           COMMIT WORK AND WAIT.     " <=== Maybe VERY important
          CATCH cx_sy_native_sql_error INTO exc_ref.
              error_text = exc_ref->get_text( ).
              Concatenate 'Table-INSERT: ' error_text Into error_text.
              MESSAGE error_text TYPE 'I'.
          ENDTRY.
        ENDLoop.     " Loop AT XY     
    END   Insert your table XY to an external database
    START: Clear Connection
        EXEC SQL.
          DISCONNECT 'TEST_FH'
        ENDEXEC.
    END : Clear Connection
    Hope it works
    Best wishes
    Frank

Maybe you are looking for