Query SQL to split the lines based on the amount

I have the data in the following format in the table.

ORDER_ID PRODUCT_ID QUANTITY

O1 A1   3

I need to write the sql query to divide the data in following format:

ORDER_ID PRODUCT_ID QUANTITY

O1 A1   1

O1 A1   1

O1 A1   1

Query must split the data based on the value in the quantity column.

Thank you

Developer

Hello

create table order_items (
  order_id varchar2(2),
  product_id varchar2(2),
  quantity number
)
;
insert into order_items values ('O1', 'A1', 3)
;
-- Recursive Subquery Factoring
with item(order_id, product_id, quantity) as (
  select
    order_id, product_id, quantity
  from order_items
  union all
  select
    order_id, product_id, quantity - 1
  from item
  where quantity > 1
)
select
  order_id, product_id, 1 quantity
from item
order by order_id
;
drop table order_items purge
;

Table ORDER_ITEMS created.

1 row inserted.

OR PR   QUANTITY
-- -- ----------
O1 A1          1
O1 A1          1
O1 A1          1

Table ORDER_ITEMS dropped.

Tags: Database

Similar Questions

  • SQL query for roll up the amounts from more down to the highest level

    with data (select child 'C', 'P' as a parent, 11 amount of double

    the Union all select 'C1', 'C',-2 double

    Union all select 'C2', 'C', 3 double

    the Union all select 'C3', 'C',-8 double

    Union all select 'C4', 'C', 10 double

    Union all select 'C11', 'C1', 7 double

    the Union of all select them 'C12', 'C1', double 12

    Union all select "C21", "C2", 5 double

    Union all select "C22", "C2", 9 double

    Union all select 'C31', 'C3', 6 double

    the Union all select 'C32', 'C3',-4 double

    the Union all select 'C41', 'C4',-3 double

    the Union of all select them "C42', 'C4' 13 doubles

    the Union of all select them "C111", "C11", 16 doubles

    Union all select 'C121","C12", 8 double

    ) Select * from given by 2

    Hi Experts,

    I have the following table with the child-parent relationship which I would like to roll up from a lower to a higher level. The problem here is that I'm moving the level I should replace the amount for a parent with the overall value of his children and grand total aggregate amount should be c

    For example; In the example given the c111 data roll up to c11 as 16 (Please note: the amount for c11 is 7 should not be added to 16 rather replaced by 16) that more should roll up to c1.

    That means c1 = c11c12; c11 = c111 = 16 Yes, c1 = 16instread 12 16712.

    Since it is an intermediate table, I don't have any control over how many levels it can contain.

    So dynamically, I need a rollup query and group the amount of a lower to a higher level from the bottom.

    Is this possible? I look forward to any help. Thanks in advance.

    SQL > data
    () 2
    3. Select 'C' child, 'P' as a parent, 11 amount of double
    4 union all select 'C1', 'C',-2 double
    5 Union all select them 'C2', 'C', 3 double
    6 Union all select them 'C3', 'C',-8 double
    7 union all select 'C4', 'C', 10 double
    8 union all select 'C11', 'C1', the double 7
    9 Union all select 'C12', 'C1', 12 dual from
    all the 10 union select "C21", "C2", 5 double
    all the 11 union select "C22", "C2", 9 double
    12 union all select 'C31', 'C3', 6 double
    all the 13 union select 'C32', 'C3',-4 double
    14 union all select 'C41', 'C4',-3 double
    all the 15 union select 'C42', 'C4', 13 from dual
    all the 16 union select 'C111","C11", 16 of the double
    all the 17 union select 'C121","C12", 8 double
    18)
    19, data1
    20 in accordance with
    (21)
    22 Select parent
    23, child
    24, lpad ('-', (level 1) * 3, '-'). parent tree_structure
    25, amount
    26, case when connect_by_isleaf = 1 then amount 0 otherwise end amount_leaf
    27 data
    starting 28 with parent = 'P '.
    29 to connect
    30 per parent prior child =
    31)
    32 Select parent as a node
    33, tree_structure
    34, amount_sum
    35 of Data1
    model 36
    size 37 by
    (38)
    39 children
    40, parent
    41)
    42 measures
    (43)
    44 amount_leaf as the amount
    45, tree_structure
    46, 0 amount_sum
    47)
    automatic control of 48 rules
    (49)
    50 amount_sum [none, none] = amount [cv (), cv ()] + nvl (sum (amount_sum) [all cv (child)], 0)
    (51);

    ŒIL TREE_STRUCTURE AMOUNT_SUM BLINK
    --- ------------------------- ----------


    P   P                                 50
    C   ---C                              24
    C1  ------C1                          16
    C11 ---------C11                      16
    C1  ------C1                           8
    C12 ---------C12                       8
    C   ---C                              14
    C2  ------C2                           5
    C2  ------C2                           9
    C   ---C                               2
    C3  ------C3                           6
    C3  ------C3                          -4
    C   ---C                              10
    C4  ------C4                          -3
    C4  ------C4                          13

    15 selected lines.

  • query SQL related beaking the string based on the position of the string

    Hello

    I've got coloumn in this way

    city_state
    ----------------
    Texas tx
    sanantanio tx
    New York ny
    nj newjersy
    NewYork
    newjersy
    Landon 1000

    I want to get the last characters after the string space (for example: texas tx) tx only, which means that I want only to break the chains that have space in 3rd place during the counting of the chain from the rear. other records that do not match as above indicated should decoded as "unknown".
    (for example 'landon 1000' decode as unknown or "New York" decodes Unknown)

    can someone please help with this query.

    Thank you
    RAM

    Hi, Ram,

    You can use SUBSTR to get the antepenultimate character (in other words, the 3rd from the end: I don't get to use that Word every day) and the last 2 characters.
    If the 2nd argument SUBSTR is a negative number, this means the end count.
    For example:

    SELECT  city_state
    ,       CASE
               WHEN  SUBSTR (city_state, -3, 1) = ' '
               THEN  SUBSTR (city_state, -2)
               ELSE  'Unknown'
            END     AS state
    FROM    table_x
    ;
    
  • What could be the query to get the amount to spend on a product name in EBS?

    Hi Experts,

    I need help to write a query in EBS for the amount to be spent for any given product name and category of high-level (Segment1).

    It may be a different query two or one only. Please answer if someone knows how to do. I need for the objective test.

    Thanks in advance.

    All good Chassey here.

    You can try the SQL below.

    MSIB.Description, mcb.segment1, SUM(pla.quantity*pla.unit_price) SELECT total_spend
    Of
    po_lines_all pla,
    mtl_categories_b mcb,
    mtl_system_items_b msib
    WHERE pla.category_id = mcb.category_id
    AND pla.item_id = msib.inventory_item_id
    AND msib.organization_id =
    GROUP BY msib.description, mcb.segment1

    If you do not use the PO_LINES_ALL, is there any other source you plan to use for spending.

    MCB.segment1, SUM(pla.quantity*pla.unit_price) SELECT total_spend
    Of
    po_lines_all pla,
    mtl_categories_b BCP
    WHERE pla.category_id = mcb.category_id
    GROUP BY mcb.segment1

    and did not no need to table po_lines_all. I do between OBIEE reports and data of EBS test validation. In the report I keep only the name of the product and the amount to be spent to make it simple. Now, I need to verify that the values are the same in the report and the EBS. That's the criteria.

    Thank you
    Nathalie

  • SQLCL - retrieves different number of lines based on the style of SQL

    SQLcl: Release 4.1.0 Release Candidate on Tue Jul 14 10:24:05 2015
    Copyright (c) 1982, 2015, Oracle.  All rights reserved.
    

    I need spool on CSV for 2 SQL statements for a thorough comparison. So, my appearance of SQL statements like this,

    set sqlformat csv
    set trimspool on
    spool file1.csv
    select blah blah blah from some_table;
    spool off
    

    Second SQL looks like this,

    set sqlformat csv
    set trimspool on
    spool file1.csv
    with s1 as (sql_statement)
    ,s2 as (sql_Statement)
    select blah blah from table join s1 ... join s2 ... ;
    spool off
    

    the two SQLs are stored in individual files, when I run the first sql, it reads 4400 + lines as expected and generates a CSV. When I run the second SQL (which uses WITH clause), it gets only 50 lines and stops.

    Ideas or reasons for this? The second SQL is also expected to extract about 4400 lines, it's the sql developer and I can export in csv, but wait sqlcl behaves well. I guess it I'm missing something here, can someone point me to the error?

    TIA

    REDA

    I think I understand the problem, it was a classic user error. Sorry everyone, I have an obscure where clause that I completely missed. Once removed, it worked flawlessly.

    REDA

  • State of color lines based on a value in the same row

    I would like to color report lines based on a value in the same row.

    For bolting with the table 'EMP ':

    I would like job = MANAGER and Red work = CLERK to be green etc etc.

    The other example I found was the possibility of a single color either the nail or the default color.

    I'm looking for a way to do multiple colors.

    Hello

    In the model line, you can use #1 #, 2 # #, etc. to indicate where a field in the report should be released. It doesn't have to be clear - that is to say, you can use it in style tags if you wish.

    So take a query such as:

    SELECT EMPNO,
    ENAME,
    DEPTNO,
    DECODE(DEPTNO, 10, 'green', 20, 'red', 30, 'cyan', 'white') BG_COLOUR
    FROM EMP
    

    You get the column 1 = empno, 2 = ename, 3 = deptno and 4 = bg_colour. In the model line, you can then do:

    Before defining lines (implements the table):

    <table>
    <tr><td>ID</td><td>Name</td><td>Dept</td></tr>
    

    After setting (farm table) lines:

    </table>
    

    Model 1 (used for all lines) line:

    <tr style="background-color:#4#;"><td>#1#</td><td>#2#</td><td>#3#</td></tr>
    

    Then, for each row, the color that has been calculated by using the DECODE function is used in the style tag for color the background of the whole line.

    How to determine the colors, it's you. I used DECODE here, but you can use a field on the DEPT table to hold and use it in your SQL statement.

    Andy

  • SQL Loader - ignore the lines with "rejected - all null columns."

    Hello

    Please see the attached log file. Also joined the table creation script, data file and the bad and throw the files after execution.

    Sqlldr customer in the version of Windows-

    SQL * Loader: release 11.2.0.1.0 - Production

    The CTL file has two clauses INTO TABLE due to the nature of the data. The data presented are a subset of data in the real world file. We are only interested in the lines with the word "Index" in the first column.

    The problem we need to do face is, according to paragraph INTO TABLE appears first in the corresponding CTL lines file to the WHEN CLAUSE it would insert and the rest get discarded.

    1. statement of Create table : create table dummy_load (varchar2 (30) name, number, date of effdate);

    2. data file to simulate this issue contains the lines below 10. Save this as name.dat. The intention is to load all of the rows in a CTL file. The actual file would have additional lines before and after these lines that can be discarded.

    H15T1Y Index | 2. 19/01/2016 |

    H15T2Y Index | 2. 19/01/2016 |

    H15T3Y Index | 2. 19/01/2016 |

    H15T5Y Index | 2. 19/01/2016 |

    H15T7Y Index | 2. 19/01/2016 |

    H15T10Y Index | 2. 19/01/2016 |

    CPDR9AAC Index | 2. 15/01/2016 |

    MOODCAVG Index | 2. 15/01/2016 |

    H15TXXX Index | 2. 15/01/2016 |

    H15TXXX Index | 2. 15/01/2016 |

    3. the CTL file - name.ctl

    DOWNLOAD THE DATA

    ADD

    IN THE TABLE dummy_load

    WHEN (09:13) = "Index".

    TRAILING NULLCOLS

    (

    COMPLETED name BY ' | ',.

    rate TERMINATED BY ' | '.

    COMPLETED effdate BY ' | '. ' TO_DATE (: effdate, "MM/DD/YYYY").

    )

    IN THE TABLE dummy_load

    WHEN (08:12) = "Index".

    TRAILING NULLCOLS

    (

    COMPLETED name BY ' | ',.

    rate TERMINATED BY ' | '.

    COMPLETED effdate BY ' | '. ' TO_DATE (: effdate, "MM/DD/YYYY").

    )

    invoke SQL loader in a file-> beats

    C:\Oracle\product\11.2.0\client\bin\sqlldr USERID = myid/[email protected] CONTROL=C:\temp\t\name.ctl BAD=C:\temp\t\name_bad.dat LOG=C:\temp\t\name_log.dat DISCARD=C:\temp\t\name_disc.dat DATA=C:\temp\t\name.dat

    Once this is run, the following text appears in the log file (excerpt):

    Table DUMMY_LOAD, charged when 09:13 = 0X496e646578 ('Index' character)

    Insert the option in effect for this table: APPEND

    TRAILING NULLCOLS option in effect

    Column Position Len term Encl. Datatype name

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

    NAME                                FIRST     *   |       CHARACTER

    RATE                                 NEXT     *   |       CHARACTER

    EFFDATE NEXT * |       CHARACTER

    SQL string for the column: ' TO_DATE (: effdate, "MM/DD/YYYY").

    Table DUMMY_LOAD, charged when 08:12 = 0X496e646578 ('Index' character)

    Insert the option in effect for this table: APPEND

    TRAILING NULLCOLS option in effect

    Column Position Len term Encl. Datatype name

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

    NAME                                 NEXT     *   |       CHARACTER

    RATE                                 NEXT     *   |       CHARACTER

    EFFDATE NEXT * |       CHARACTER

    SQL string for the column: ' TO_DATE (: effdate, "MM/DD/YYYY").

    Record 1: Ignored - all null columns.

    Sheet 2: Cast - all null columns.

    Record 3: Ignored - all null columns.

    Record 4: Ignored - all null columns.

    Sheet 5: Cast - all null columns.

    Sheet 7: Discarded - failed all WHEN clauses.

    Sheet 8: Discarded - failed all WHEN clauses.

    File 9: Discarded - failed all WHEN clauses.

    Case 10: Discarded - failed all WHEN clauses.

    Table DUMMY_LOAD:

    1 row loaded successfully.

    0 rows not loaded due to data errors.

    9 lines not loading because all WHEN clauses were failed.

    0 rows not populated because all fields are null.

    Table DUMMY_LOAD:

    0 rows successfully loaded.

    0 rows not loaded due to data errors.

    5 rows not loading because all WHEN clauses were failed.

    5 rows not populated because all fields are null.


    The bad file is empty. The discard file has the following

    H15T1Y Index | 2. 19/01/2016 |

    H15T2Y Index | 2. 19/01/2016 |

    H15T3Y Index | 2. 19/01/2016 |

    H15T5Y Index | 2. 19/01/2016 |

    H15T7Y Index | 2. 19/01/2016 |

    CPDR9AAC Index | 2. 15/01/2016 |

    MOODCAVG Index | 2. 15/01/2016 |

    H15TXXX Index | 2. 15/01/2016 |

    H15TXXX Index | 2. 15/01/2016 |


    Based on the understanding of the instructions in the CTL file, ideally the first 6 rows will have been inserted into the table. Instead the table comes from the line 6' th.

    NAMERATEEFFDATE
    H15T10Y Index2January 19, 2016



    If the INTO TABLE clauses were put in the CTL file, then the first 5 rows are inserted and the rest are in the discard file. The line 6' th would have a ""rejected - all columns null. "in the log file. "


    Could someone please take a look and advise? My apologies that the files cannot be attached.

    Unless you tell it otherwise, SQL * Loader assumes that each later in the table and what clause after the first back in the position where the previous left off.  If you want to start at the beginning of the line every time, then you need to reset the position using position (1) with the first column, as shown below.  Position on the first using is optional.

    DOWNLOAD THE DATA

    ADD

    IN THE TABLE dummy_load

    WHEN (09:13) = "Index".

    TRAILING NULLCOLS

    (

    name POSITION (1) TERMINATED BY ' | '.

    rate TERMINATED BY ' | '.

    COMPLETED effdate BY ' | '. ' TO_DATE (: effdate, "MM/DD/YYYY").

    )

    IN THE TABLE dummy_load

    WHEN (08:12) = "Index".

    TRAILING NULLCOLS

    (

    name POSITION (1) TERMINATED BY ' | '.

    rate TERMINATED BY ' | '.

    COMPLETED effdate BY ' | '. ' TO_DATE (: effdate, "MM/DD/YYYY").

    )

  • Result of text SQL with Chr (10) (line break) NOT carried over to the HTP. P Javascript Mailto

    [4.2.1.00.08 Express application.]

    Hello, Super gurus!

    Maybe I am still not able to wrap my head around quotes and concatenations, as in this post Re: Mailto PL/SQL block with window.location.href, I would like to ask for your help again.

    I can't get a NEW LINE character to work in my htp.p & javascript.

    Full article: it is an extension of what I worked on, as shown in the link above.  This time, I called a request similar, as shown below, of my 'after Submit PL/SQL anonymous block ' process:

    DECLARE
    TYPE emp_aat IS TABLE OF THE emp % ROWTYPE;
    l_employees emp_aat;
    v_result varchar2 (5000): = ";
    BEGIN
    SELECT *.
    LOOSE COLLECTION l_employees
    WCP
    ORDER BY ename;

    BECAUSE me in 1... l_employees. COUNTY
    LOOP
    v_result: = v_result | l_employees (i) .ename | ' -  '
    || ' Job: ' | l_employees (i) .job | ' ';
    || Chr (10);
    END LOOP;
    Dbms_output.put_line (v_result);
    END;

    The above works well with the Chr (10), where each outcome starts on a new line:

    ADAMS - job: CLERK

    ALLEN - job: SALESMAN

    BLAKE - job: MANAGER

    CLARK - job: MANAGER

    Further down on my PL/SQL block process, the problem I have is that I can not get the v_result is displayed as you like, with the new line:

    HTP.p ("< body > '");

    HTP.p ("< script type =" text/javascript "> '");

    HTP.p ('window.location.href = "mailto:" |) v_logged_on_user_email | ';'

    ||'? "subject = salary increase Request"

    |' & cc ='

    || v_hr_email

    ||';'

    |' & body = '
    ||' \n "

    ||' Two hundred per cent increase for these people to chance! "

    ||' \r\n "

    || v_result

    ||'";'

    );

    HTP.p ("< /script >" ");

    HTP.p ("< /body >" ");

    As a matter of fact, these '\n' and '\r\n' above do seem to not work at all.  And the body of my email has just 1 big piece:

    ADAMS - job: COMMITTED ALLEN - job: SALESMAN BLAKE - job: MANAGER CLARK - job: MANAGER

    Issues related to the:

    -Should I replace "Chr (10)" in my SQL query with something so that javascript would recognize?

    -How is "\n" does not work as expected?

    Please let me know if I did something wrong with the foregoing, and that can be done to correct it.

    Thank you very much!

    It is a HTML problem, you will get best responses from stackoverflow.

    Try % OA

    HTML - mailto link several lines of body - Stack Overflow

  • Generating lines based on the value of the column?

    Hi all

    I would like to know if there is a function that can help me in creating lines based on a column value and, if so, which. I'm on version 11.2.0.3.0

    for example, I have these data in the table:
    ID O A C
    1 5 3 5
    2 9 2 3

    Where ID is an identifier unique record and column C contains the number of records, I would have returned for this ID. In this example, the folder with the ID 1 would be repeated 5 times and the folder with the id 2 would be repeated 3 times. The result would look like this:

    ID O A C
    1 5 3 5
    1 5 3 5
    1 5 3 5
    1 5 3 5
    1 5 3 5
    2 9 2 3
    2 9 2 3
    2 9 2 3

    Column C contains the number of repetitions Records and is defined as a positive integer > = 1.

    Of course, in real life, the table contains (at this time) 41 M number of records and the value of C can vary between 1 and 554, hardcode on the example above values is not possible.

    Any pointers in the right direction are much appreciated.

    Kind regards
    Lennert
    SQL> ed
    Wrote file afiedt.buf
    
      1  with t as (select 1 as id, 5 as c from dual union all
      2             select 2, 3 from dual)
      3  --
      4  select id, c
      5  from   t
      6  connect by level <= c
      7          and id = prior id
      8*         and prior sys_guid() is not null
    SQL> /
    
            ID          C
    ---------- ----------
             1          5
             1          5
             1          5
             1          5
             1          5
             2          3
             2          3
             2          3
    
    8 rows selected.
    
  • How to query a line based on its rownum

    Hi all
    What is the best way to interrogate a line based on its rownum? Suppose I have the following query:
    select first_name from employees where rownum<5;
    FIRST_NAME
    --------------------
    Ellen
    Sundar
    Mozhe
    David
    Ellen has rownum 1, Sundar 2 and so on. How can I do it if I just want to ask a line where Mozhe's name, which is rownum 3?

    Best regards
    Val

    You said:

    >
    According to its availability
    >

    Is not calculate it? What do you mean by 'availability' in this context?

    What you can do, is something like this:

    select empno, ename
    from (
       select empno, ename, rownum rn
       from (
         select empno, ename
         from scott.emp
         order by ename
       )
       where rownum <= 3
    )
    where rn = 3;
    

    You need something to order by.
    Then, you create an internal selection with this order by.
    Then you select the inside where select rownum<=>
    And then you select just one third.
    So select the above gets you the third order of the employee by name.

  • Query SQL Report with condition (multiple settings) at the point of the apex?

    Hi all

    I have a small problem and cannot find a solution.

    I need to create reports based on a query, SQL or I.R. Nothing hard here.
    I need to add the WHERE clause dynamically with javascript to an element of the Apex.
    Even once is not very difficult. I set the agenda of the Summit, put my query like this "SELECT * FROM MYTAB WHERE COL1 =: P1_SEARCH" then I call the page by setting the P1_SEARCH value. For example, COL1 is rowid. It works very well.

    But here's my problem. Consider that P1_SEARCH contains several ROWID, and I don't know the number of these values,
    (no I don't create a large number of items and create a query with so much GOLD!), I would sotheming like "SELECT * FROM MYTAB WHERE ROWID IN (: P1_SEARCH) with something like: ROWID1, ROWID2 in P1_SEARCH."

    I also tried: 'ROWID1, ROWID2' and 'ROWID1', 'ROWID2 '.
    but I can't get anything else than the mistake of filter. It works with a value, but as soon as there are two values or more, it seems that the Apex is unable to read the string.


    How can I do it please?

    Thanks for your help.

    Max

    mnoscars wrote:

    But here's my problem. Consider that P1_SEARCH contains several ROWID, and I don't know the number of these values,
    (no I don't create a large number of items and create a query with so much GOLD!), I would sotheming like "SELECT * FROM MYTAB WHERE ROWID IN (: P1_SEARCH) with something like: ROWID1, ROWID2 in P1_SEARCH."

    I also tried: 'ROWID1, ROWID2' and 'ROWID1', 'ROWID2 '.
    but I can't get anything else than the mistake of filter. It works with a value, but as soon as there are two values or more, it seems that the Apex is unable to read the string.

    For a standard report, see + {message identifier: = 9609120} +.

    For an IR - and improve safety by avoiding the risk of SQL Injection, use a collection containing the values in a column instead of a CSV list:
    {code}
    SELECT * FROM MYTAB WHERE ROWID IN (SELECT c001 FROM apex_collections WHERE collection_name = "P1_SEARCH")
    {code}
    (Please close duplicate threads spawned by your original question.)

  • sql Update query after matching with the string

    I am trying to reach the query that updates a table column with the value of the other table, after that he finds an exact match.

    So here's the table data and sample to create.
    create table code1 
    (
        codeid number,
        codedesc varchar2(60)
    );
    
    Insert into code1 values ( 1,'R1 CONTRACTS');
    
    Insert into code1 values ( 2,'R2 CONTRACTS');
    
    Insert into code1 values ( 3,'R3 CONTRACTS');
    
    Insert into code1 values ( 4,'R5 CONTRACTS');
    
    Insert into code1 values ( 5,'R9 CONTRACTS');
    
    Insert into code1 values ( 6,'R10 CONTRACTS');
    
    create table table1 
    (   
        tablekey number,
        prefix  varchar2(25),
        codedesc    varchar2(60)
    );
    
    Insert into table1(tablekey,prefix) values (1,'1001PAC');
    
    Insert into table1(tablekey,prefix) values (2,'1001MXT');
    
    Insert into table1(tablekey,prefix) values (3,'1002PAE');
    
    Insert into table1(tablekey,prefix) values (4,'1003PCS');
    
    Insert into table1(tablekey,prefix) values (5,'1004BDX');
    
    Insert into table1(tablekey,prefix) values (6,'1005PAC');
    
    Insert into table1(tablekey,prefix) values (7,'1006PAC');
    
    Insert into table1(tablekey,prefix) values (8,'1007LDR');
    
    Insert into table1(tablekey,prefix) values (9,'1009LCR');
    
    Insert into table1(tablekey,prefix) values (10,'1010LBR');
    
    Insert into table1(tablekey,prefix) values (11,'ABCDEF');
    I'm writing a query that would update the value of column - codedesc (currently Null) of the table1 table: after it is a string of column - table code1 codedesc.

    The logic for the match is, - take - 2nd column of table-codedesc code value and get 2 characters. For example, when the string is - R1 CONTRACTS, the string will be 1. (Select substr ("R1 CONTRACTS, 2, 2) of the double). -Output will be 1.

    Now,.
    Look in table 1 for the 3rd position of the prefix that corresponds to the string returned by the query above. So, if the prefix is '1001PAC', it should look for 2 value of figures from the 3rd position. So, in this case it will be 01. Digitally 01 and 1 are equal, then the match is found for this line in the table1 table, so we will need to update the value of the column codedesc with the "contracts of R1.
        tablekey,    prefix            codedesc    
    ---------- ------------------------------------------------------------
    
          1               1001PAC     R1 CONTRACTS    -- Needs to be update with this value. 
          2               1001MXT     R1 CONTRACTS
          3               1002PAE      R2 CONTRACTS
    ...
          11             ABCDEF                                --Null ( No Need to update when no match found).
    SQL> select * from v$version;
    
    BANNER
    ----------------------------------------------------------------
    Oracle Database 10g Release 10.2.0.4.0 - 64bit Production
    PL/SQL Release 10.2.0.4.0 - Production
    CORE    10.2.0.4.0      Production
    TNS for Linux: Version 10.2.0.4.0 - Production
    NLSRTL Version 10.2.0.4.0 - Production
    Appreciate your help.

    Hello

    You want to avoid TO_NUMBER, given that will cause an error if even a line has a number no (except space) in the wrong place.
    Use RTRIM to remove extra spaces at the end of the match_key and LPAD to add '0', if necessary, at the beginning:

    MERGE INTO     table1          dst
    USING   (
              SELECT  LPAD ( RTRIM ( SUBSTR ( codedesc
                                     , 2
                                   , 2
                                   )
                              )
                         , 2
                         , '0'
                         )          AS match_key
              ,     codedesc
              FROM     code1
         )               src
    ON     (src.match_key     = SUBSTR ( dst.prefix
                           , 3
                         , 2
                         )
         )
    WHEN MATCHED THEN UPDATE
         SET     dst.codedesc     = src.codedesc
    ;
    

    Thanks for posting the CREATE TABLE and INSERT statements; It's very useful!

  • PL/SQL Query return function, adding the column links

    Hi all

    I'm working on a SQL report with the area type = function from PL/SQL Query to return
    All columns are generated dynamically based on my mapping table and a column of ID.
    So whenever the page is loaded, according to the ID mapping table returns a set of columns in a particular order.
    So not only the columns are dynamic, but the order of the columns varies also.
    But the first 1 column is standard (it doesn't come from the mapping table) and is coded in my pl/sql block hard.

    I'm fighting with the addition of a link to this column. The link must be a Javascript function which takes the parameters in the form of 2 columns in the mapping table.
    My pl/sql block is something like that...
    v_select := 'SELECT <g href=javascript:f_report1(#map_id#,#comments#)><img src=""></a> as report1, ';  // g=a
    v_cols := 'contains all columns from the mapping table based on a ID(hidden item)';
    v_from := 'FROM table';
    v_where := 'where condition is put in here';
    v_query := v_select||v_from||v_where;
    return v_query;
    Now, I'm not able to transmit the values of this #map_id # and #comments # correctly. I tried so many different combinations of channels, but could not make it work.

    I'm not sure that the order of this map_id and commentscolumn and therefore cannot connect through the report attributes.
    How can I go to a column value to the function?



    Thank you
    Dippy

    This should work if all goes well:

    v_select := q'[ SELECT '' as chart, ]';
    

    Published by: Dimitri Gielis on May 20, 2010 20:10

  • Production PL/SQL query: can not find the error

    I have a PL/SQL which produces a query for me, which is used to fill out a report. I use this to supply a filter/search form. Since I want to only filter using xxx movies WHERE = yyy when yyy actually has something else NULL, I use a PL/SQL script in the query I need to produce. However, it does not work as expected and I can't understand why. Here is my code:
    DECLARE
      query VARCHAR(1000);
    BEGIN
      query := 'SELECT * FROM F_OBJEKTE WHERE 1=1 ';
      IF :P15_REGION != null THEN
        query := query || 'AND REGION = :P15_REGION ';
      END IF; 
      RETURN query;
    END;
    However, the report still contains all lines, as if P15_REGION has not been defined - and so I guess that the script never enters the IF part. Everyone around who can enlighten me, why it is?

    Just another little thing: is there a way I can print debugging messages I see when I press the "Debug" button on the lower bar of APEX? It would help a lot of debugging such PL/SQL functions.

    Try changing

    IF: P15_REGION! = null THEN

    TO

    IF: P15_REGION is not null THEN

  • Improve a simple select query that uses all the lines.

    Hi all

    Excuse me if the question is too dumb. Here is my code
    SQL> select * from v$version;
    
    BANNER
    ----------------------------------------------------------------
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Prod
    PL/SQL Release 10.2.0.1.0 - Production
    CORE    10.2.0.1.0      Production
    TNS for 32-bit Windows: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - Production
    
    Elapsed: 00:00:00.07
    SQL> show parameter optim
    
    NAME                                 TYPE        VALUE
    ------------------------------------ ----------- ------------------------------
    object_cache_optimal_size            integer     102400
    optimizer_dynamic_sampling           integer     2
    optimizer_features_enable            string      10.2.0.1
    optimizer_index_caching              integer     0
    optimizer_index_cost_adj             integer     100
    optimizer_mode                       string      ALL_ROWS
    optimizer_secure_view_merging        boolean     TRUE
    plsql_optimize_level                 integer     2
    
    SQL> explain plan for select SUM(decode(transaction_type,'D',txn_amount,0)) payments_reversals,
      2          SUM(decode(transaction_type,'C',txn_amount,0)) payments,primary_card_no,statement_date
      3             from credit_card_pymt_dtls  group by primary_card_no,statement_date;
    
    Explained.
    
    SQL> select * from table(dbms_xplan.display);
    
    PLAN_TABLE_OUTPUT
    -----------------------------------------------------------------------------------------------------------------------
    -----------------------------------
    Plan hash value: 2801218574
    
    ----------------------------------------------------------------------------------------------------
    | Id  | Operation          | Name                  | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     |
    ----------------------------------------------------------------------------------------------------
    |   0 | SELECT STATEMENT   |                       |  1912K|    56M|       | 21466   (3)| 00:04:18 |
    |   1 |  SORT GROUP BY     |                       |  1912K|    56M|   161M| 21466   (3)| 00:04:18 |
    |   2 |   TABLE ACCESS FULL| CREDIT_CARD_PYMT_DTLS |  1912K|    56M|       |  4863   (3)| 00:00:59 |
    ----------------------------------------------------------------------------------------------------
    
    9 rows selected.
    
    SQL> select index_name,index_type
      2  from all_indexes
      3  where table_name = 'CREDIT_CARD_PYMT_DTLS';
    
    INDEX_NAME                     INDEX_TYPE
    ------------------------------ --------------------
    INDX_TRANTYPE                  BITMAP
    INDX_PCARD                     NORMAL
    INDX_PSTATEMENT_DATE           NORMAL
    The query uses all records in the CREDIT_CARD_PYMT_DTLS table. Transaction type will be either 'C' or '.

    CREDIT_CARD_PYMT_DTLS has 2 million lines and the qury will display 1.5 million lines. Table statisticas are up to date.

    The query takes now almost 5 minutes. Y thaere a way to reduce the time?

    Our DB server has 8 processors and 8 GB of memory. Is it authentic?

    Thanks in advance.

    Published by: user11115924 on April 29, 2009 02:43
    All columns used in the query are already indexed. (Of course, not only for this query.)

    I should not get too hung up the full Table Scan necessarily - Oracle makes a decision, and even with your new index, he still thinks it is the most effective way to recover the data.

    Did you collect statistics on this new index?

    You have created the index with:

    TO_CHAR("STATEMENT_DATE",'MON-RRRR')
    

    Yet, you seem to be just by selecting statement_date in your query: Oracle cannot use the index (according to functions) in this case!

    If you have only a small number of columns in this table, you can consider an Table of Index organized (ITO), then the table itself is a clue.

    I'd be more inclined to optimize the complete analysis of the table and the creation of other clues, I would say, have you tried the PARALLEL tip?

Maybe you are looking for

  • Satellite Pro L50 - B - no display at the start of

    Hello Problems with getting my L50 - B to initialize display. Everything else is running, but the display won't start at all - I just get a full black screen. I tried without success to the following: (1) connection to an external display to work2 po

  • Disabled system: 57733976

    Things became slower after a year, so I decided to perform a clean install of Win8.1However, when I tried to get into the BIOS to change the boot order to boot from dvd, asked me to enter the admin password. So I entered the password I put in place e

  • Problem reinstalling OSX

    Reinstalling OSX of original disc recognizes later Apple wireless keyboard. How to cross this page? Post edited by: TEPLANNER (corrected typo in the title)

  • Lenovo V470/V570 starting problems

    I bought a laptop Lenovo V570 10j ag from Best Buy. It worked really good for 8 days, and then got stuck at the level of the cursor of the start screen rotation. I tried several methods to fix this withdrawal including it form power source, remove th

  • Scan to pdf deskjet j3680 all-in-one

    Questions: 1) unable to scan to a PDF file and have tried reinstalling the drivers, 2) I'm not able to locate the center of HP solutions on my computer - I looked in 'Programs' and 'Control Panel '? Operating system - Windows 7 Ultimate 32 bit Help,