"Balance forward" SQL statement

Has anyone developed a SQL statement that allows balances to be carried forward? Would a UNION query possibly work?
Here's my example where I need to join 3 tables and show results. Based on the example data below, I am looking for a query that allows me to illustrate that the Acrobat 9 Installed Software instances are consuming a license capacity of 6, leaving a balance of 4 that can be applied to the Acrobat 8 Installed Software Instances.
Table: LICENSE
LICENSENUM     SWLICENSE          LICENSECAPACITY
'1001'          'Adobe Acrobat 9'     '10'
Table: LICENSESW
LICENSENUM     SWPRODUCT     PRECEDENCE
'1001'     'Acrobat 9'     '1'
'1001'     'Acrobat 8'     '2'
Table: INSTALLEDSW
INSTALLEDSW
'Acrobat 9'
'Acrobat 9'
'Acrobat 9'
'Acrobat 9'
'Acrobat 9'
'Acrobat 9'
'Acrobat 8'
'Acrobat 8'
'Acrobat 8'
'Acrobat 8'
'Acrobat 8'
I can write a select to do total counts, but this does not allow me to carry a balance forward to be applied to Acrobat 8 (precedence 2).
select LICENSE.SWLICENSE, LICENSE.LICENSECAPACITY, count(INSTALLEDSW.INSTALLEDSW) as INSTALLED_COUNT
from LICENSE, LICENSESW, INSTALLEDSW
where LICENSE.LICENSENUM = LICENSESW.LICENSENUM
AND LICENSESW.SWPRODUCT = INSTALLEDSW.INSTALLEDSW
group by LICENSE.SWLICENSE, LICENSE.LICENSECAPACITY;
Results:
SWLICENSE          LICENSECAPACITY          INSTALLED_COUNT
'Adobe Acrobat 9'     '10'               '11'
I need results that look like this, where the balance of 4 is carried forward after the first row:
SWLICENSE          LICENSECAPACITY          INSTALLED_PRODUCT     INSTALLED_COUNT
'Adobe Acrobat 9'     '6'               'Acrobat 9'          '6'
'Adobe Acrobat 9'     '4'               'Acrobat 8'          '5'

Not easy to follow your example data, but if I demonstrate what I think you are trying to achieve using the emp table, you may be able to see if it helps...
SQL> select deptno, empno, ename
  2        ,count(*) over (partition by deptno) as dept_count
  3        ,count(*) over (partition by deptno) - row_number() over (partition by deptno order by empno) as remaining
  4  from   emp
  5  order by deptno, empno;
    DEPTNO      EMPNO ENAME      DEPT_COUNT  REMAINING
        10       7782 CLARK               3          2
        10       7839 KING                3          1
        10       7934 MILLER              3          0
        20       7369 SMITH               5          4
        20       7566 JONES               5          3
        20       7788 SCOTT               5          2
        20       7876 ADAMS               5          1
        20       7902 FORD                5          0
        30       7499 ALLEN               6          5
        30       7521 WARD                6          4
        30       7654 MARTIN              6          3
        30       7698 BLAKE               6          2
        30       7844 TURNER              6          1
        30       7900 JAMES               6          0
14 rows selected.using the analytical functions count() and row_number() (you can use others such as sum(), avg(), lag(), lead() etc. as required) you can do processing that carries forward, backwards or across "groups" (aka partitions) of data.

Similar Messages

  • SQL statement running balance query with previous balance taken into account

    Hi Guys
    I have a SQL statement which caclulates the running balance
    for a list of transactions in a transactions table. This SQL
    statement is as follows:
    SELECT transID, debit, credit,
    (SELECT SUM(debit-credit)
    FROM transactions as D1
    WHERE D1.transID <= D0.transID) AS balance
    FROM transactions AS D0
    The only problem I'm having is that I have to display
    transactions between a particular date range. I have for eg.
    transID, transDate, debit, credit fields in my db.
    However the problem I'm having is that when the transaction
    records are pulled out for the specified date range the balances
    are only calculated for those records. I need someway of having a
    balance b/f (brought forward) so that the selected records use that
    as a 'starting' balance and then calculate the running balance as
    normal.
    Any easy solutions?
    Many, many thanks for your help in advance.
    All the best
    Wesley

    You'd need to determine the b/f then apply it against the
    transaction records when they are pulled for a date range. So if
    the date range is
    Feb 1st, 2009 -> Feb 28th, 2009
    You'd need to also get the previous balance in a separate
    query, then use it to correctly display the running balance when
    you output the date range.
    I suppose a simpler way involving a little more DB work (and
    possibly lots of coding) is to store the current balance as well
    with each transaction; then when performing a date range you'd have
    the balance as well and not have to calculate it on the fly.

  • There is an unclosed comment block in the SQL statement. Ensure that there are balanced "/*" and "*/" comment markers in the SQL statement.

    I get this error - when I try a Multi-line comment entry - by using the /* and */
    "There is an unclosed comment block in the SQL statement. Ensure that there are balanced "/*" and "*/" comment
    markers in the SQL statement."
    Even though I am entering both the /* and the */.
    I tried it many way - in the same line, in different lines etc..
    like 
    /* Select xxx from xxx */
    or
    Select xxx from xxx
    or 
    /* Select xx from xx
    Please help anyone..! ;=(

    But When I do a Help/About I see that it is 
    the SSMSE's Help About screen says "SQL Server 2005"
    However I downloaded and installed SQL Server 2014 last night and was entering queries..
    Most Select Queries work fine..
    the -- comment line works fine..then I stumbled on the /*  - */ does not work.
    Thanks.
    Well, you have two different version of SQL Server installed on your machine. Please connect again from SSMS to the SQL Server 2014.
    T-SQL Articles
    T-SQL e-book by TechNet Wiki Community
    T-SQL blog

  • HOW TO: Post a SQL statement tuning request - template posting

    This post is not a question, but similar to Rob van Wijk's "When your query takes too long ..." post should help to improve the quality of the requests for SQL statement tuning here on OTN.
    On the OTN forum very often tuning requests about single SQL statements are posted, but the information provided is rather limited, and therefore it's not that simple to provide a meaningful advice. Instead of writing the same requests for additional information over and over again I thought I put together a post that describes how a "useful" post for such a request should look like and what information it should cover.
    I've also prepared very detailed step-by-step instructions how to obtain that information on my blog, which can be used to easily gather the required information. It also covers again the details how to post the information properly here, in particular how to use the \ tag to preserve formatting and get a fixed font output:
    http://oracle-randolf.blogspot.com/2009/02/basic-sql-statement-performance.html
    So again: This post here describes how a "useful" post should look like and what information it ideally covers. The blog post explains in detail how to obtain that information.
    In the future, rather than requesting the same additional information and explaining how to obtain it, I'll simply refer to this HOW TO post and the corresponding blog post which describes in detail how to get that information.
    *Very important:*
    Use the \ tag to enclose any output that should have its formatting preserved as shown below.
    So if you want to use fixed font formatting that preserves the spaces etc., do the following:
    \   This preserves formatting
    \And it will look like this:
       This preserves formatting
       . . .Your post should cover the following information:
    1. The SQL and a short description of its purpose
    2. The version of your database with 4-digits (e.g. 10.2.0.4)
    3. Optimizer related parameters
    4. The TIMING and AUTOTRACE output
    5. The EXPLAIN PLAN output
    6. The TKPROF output snippet that corresponds to your statement
    7. If you're on 10g or later, the DBMS_XPLAN.DISPLAY_CURSOR output
    The above mentioned blog post describes in detail how to obtain that information.
    Your post should have a meaningful subject, e.g. "SQL statement tuning request", and the message body should look similar to the following:
    *-- Start of template body --*
    The following SQL statement has been identified to perform poorly. It currently takes up to 10 seconds to execute, but it's supposed to take a second at most.
    This is the statement:
    select
    from
             t_demo
    where
             type = 'VIEW'
    order by
             id;It should return data from a table in a specific order.
    The version of the database is 11.1.0.7.
    These are the parameters relevant to the optimizer:
    SQL>
    SQL> show parameter optimizer
    NAME                                 TYPE        VALUE
    optimizer_capture_sql_plan_baselines boolean     FALSE
    optimizer_dynamic_sampling           integer     2
    optimizer_features_enable            string      11.1.0.7
    optimizer_index_caching              integer     0
    optimizer_index_cost_adj             integer     100
    optimizer_mode                       string      ALL_ROWS
    optimizer_secure_view_merging        boolean     TRUE
    optimizer_use_invisible_indexes      boolean     FALSE
    optimizer_use_pending_statistics     boolean     FALSE
    optimizer_use_sql_plan_baselines     boolean     TRUE
    SQL>
    SQL> show parameter db_file_multi
    NAME                                 TYPE        VALUE
    db_file_multiblock_read_count        integer     8
    SQL>
    SQL> show parameter db_block_size
    NAME                                 TYPE        VALUE
    db_block_size                        integer     8192
    SQL>
    SQL> show parameter cursor_sharing
    NAME                                 TYPE        VALUE
    cursor_sharing                       string      EXACT
    SQL>
    SQL> column sname format a20
    SQL> column pname format a20
    SQL> column pval2 format a20
    SQL>
    SQL> select
      2             sname
      3           , pname
      4           , pval1
      5           , pval2
      6  from
      7           sys.aux_stats$;
    SNAME                PNAME                     PVAL1 PVAL2
    SYSSTATS_INFO        STATUS                          COMPLETED
    SYSSTATS_INFO        DSTART                          01-30-2009 16:25
    SYSSTATS_INFO        DSTOP                           01-30-2009 16:25
    SYSSTATS_INFO        FLAGS                         0
    SYSSTATS_MAIN        CPUSPEEDNW              494,397
    SYSSTATS_MAIN        IOSEEKTIM                    10
    SYSSTATS_MAIN        IOTFRSPEED                 4096
    SYSSTATS_MAIN        SREADTIM
    SYSSTATS_MAIN        MREADTIM
    SYSSTATS_MAIN        CPUSPEED
    SYSSTATS_MAIN        MBRC
    SYSSTATS_MAIN        MAXTHR
    SYSSTATS_MAIN        SLAVETHR
    13 rows selected.Here is the output of EXPLAIN PLAN:
    SQL> explain plan for
      2  -- put your statement here
      3  select
      4             *
      5  from
      6             t_demo
      7  where
      8             type = 'VIEW'
      9  order by
    10             id;
    Explained.
    Elapsed: 00:00:00.01
    SQL>
    SQL> select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    Plan hash value: 1390505571
    | Id  | Operation                   | Name     | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT            |          |     1 |    60 |     0   (0)| 00:00:01 |
    |   1 |  TABLE ACCESS BY INDEX ROWID| T_DEMO   |     1 |    60 |     0   (0)| 00:00:01 |
    |*  2 |   INDEX RANGE SCAN          | IDX_DEMO |     1 |       |     0   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       2 - access("TYPE"='VIEW')
    14 rows selected.Here is the output of SQL*Plus AUTOTRACE including the TIMING information:
    SQL> rem Set the ARRAYSIZE according to your application
    SQL> set autotrace traceonly arraysize 100
    SQL> select
      2             *
      3  from
      4             t_demo
      5  where
      6             type = 'VIEW'
      7  order by
      8             id;
    149938 rows selected.
    Elapsed: 00:00:02.21
    Execution Plan
    Plan hash value: 1390505571
    | Id  | Operation                   | Name     | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT            |          |     1 |    60 |     0   (0)| 00:00:01 |
    |   1 |  TABLE ACCESS BY INDEX ROWID| T_DEMO   |     1 |    60 |     0   (0)| 00:00:01 |
    |*  2 |   INDEX RANGE SCAN          | IDX_DEMO |     1 |       |     0   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       2 - access("TYPE"='VIEW')
    Statistics
              0  recursive calls
              0  db block gets
         149101  consistent gets
            800  physical reads
            196  redo size
        1077830  bytes sent via SQL*Net to client
          16905  bytes received via SQL*Net from client
           1501  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
         149938  rows processed
    SQL>
    SQL> disconnect
    Disconnected from Oracle Database 11g Enterprise Edition Release 11.1.0.7.0 - Production
    With the Partitioning, OLAP, Data Mining and Real Application Testing optionsThe TKPROF output for this statement looks like the following:
    TKPROF: Release 11.1.0.7.0 - Production on Mo Feb 23 10:23:08 2009
    Copyright (c) 1982, 2007, Oracle.  All rights reserved.
    Trace file: orcl11_ora_3376_mytrace1.trc
    Sort options: default
    count    = number of times OCI procedure was executed
    cpu      = cpu time in seconds executing
    elapsed  = elapsed time in seconds executing
    disk     = number of physical reads of buffers from disk
    query    = number of buffers gotten for consistent read
    current  = number of buffers gotten in current mode (usually for update)
    rows     = number of rows processed by the fetch or execute call
    select
    from
             t_demo
    where
             type = 'VIEW'
    order by
             id
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.00       0.00          0          0          0           0
    Execute      1      0.00       0.00          0          0          0           0
    Fetch     1501      0.53       1.36        800     149101          0      149938
    total     1503      0.53       1.36        800     149101          0      149938
    Misses in library cache during parse: 0
    Optimizer mode: ALL_ROWS
    Parsing user id: 88 
    Rows     Row Source Operation
    149938  TABLE ACCESS BY INDEX ROWID T_DEMO (cr=149101 pr=800 pw=0 time=60042 us cost=0 size=60 card=1)
    149938   INDEX RANGE SCAN IDX_DEMO (cr=1881 pr=1 pw=0 time=0 us cost=0 size=0 card=1)(object id 74895)
    Elapsed times include waiting on following events:
      Event waited on                             Times   Max. Wait  Total Waited
      ----------------------------------------   Waited  ----------  ------------
      SQL*Net message to client                    1501        0.00          0.00
      db file sequential read                       800        0.05          0.80
      SQL*Net message from client                  1501        0.00          0.69
    ********************************************************************************The DBMS_XPLAN.DISPLAY_CURSOR output:
    SQL> -- put your statement here
    SQL> -- use the GATHER_PLAN_STATISTICS hint
    SQL> -- if you're not using STATISTICS_LEVEL = ALL
    SQL> select /*+ gather_plan_statistics */
      2  *
      3  from
      4  t_demo
      5  where
      6  type = 'VIEW'
      7  order by
      8  id;
    149938 rows selected.
    Elapsed: 00:00:02.21
    SQL>
    SQL> select * from table(dbms_xplan.display_cursor(null, null, 'ALLSTATS LAST'));
    PLAN_TABLE_OUTPUT
    SQL_ID  d4k5acu783vu8, child number 0
    select   /*+ gather_plan_statistics */          * from          t_demo
    where          type = 'VIEW' order by          id
    Plan hash value: 1390505571
    | Id  | Operation                   | Name     | Starts | E-Rows | A-Rows |   A-Time   | Buffers | Reads  |
    |   0 | SELECT STATEMENT            |          |      1 |        |    149K|00:00:00.02 |     149K|   1183 |
    |   1 |  TABLE ACCESS BY INDEX ROWID| T_DEMO   |      1 |      1 |    149K|00:00:00.02 |     149K|   1183 |
    |*  2 |   INDEX RANGE SCAN          | IDX_DEMO |      1 |      1 |    149K|00:00:00.02 |    1880 |    383 |
    Predicate Information (identified by operation id):
       2 - access("TYPE"='VIEW')
    20 rows selected.I'm looking forward for suggestions how to improve the performance of this statement.
    *-- End of template body --*
    I'm sure that if you follow these instructions and obtain the information described, post them using a proper formatting (don't forget about the \ tag) you'll receive meaningful advice very soon.
    So, just to make sure you didn't miss this point:Use proper formatting!
    If you think I missed something important in this sample post let me know so that I can improve it.
    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/                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Alex Nuijten wrote:
    ...you missed the proper formatting of the Autotrace section ;-)Alex,
    can't reproduce, does it still look unformatted? Or are you simply kidding? :-)
    Randolf
    PS: Just noticed that it actually sometimes doesn't show the proper formatting although the code tags are there. Changing to the \ tag helped in this case, but it seems to be odd.
    Edited by: Randolf Geist on Feb 23, 2009 11:28 AM
    Odd behaviour of forum software                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • TestStand Open SQL Statement does not support SQL's ORDER BY clause???

    TestStand 1.0.3
    Windows 2000 SP1
    SQL Server 2000 Personal
    You've got to be kidding me...
    It appears that the built-in TestStand Open SQL Step does NOT support the
    "ORDER BY" clause in the SELECT statement, even though the documentation
    says it does. Is this true?
    I have an Open SQL Statement query:
    "SELECT * FROM [MyTable] WHERE ([Batch ID]=1234)"
    it works fine, returning a correct record count 120 records. If I change
    the Open SQL Statement query simply by adding an ORDER BY clause, such as:
    "SELECT * FROM [MyTable] WHERE ([Batch ID]=1234) ORDER BY [MyField] ASC"
    it returns a record count of zero. I know that "MyField" exists in the
    MyTable table and contains valid data. The
    second query works fine in SQL
    Server Enterprise Manager.
    Am I missing something? Is it true that the TestStand Open SQL Step does
    NOT support the "ORDER BY" clause? If not, what &#$!ing good is it and why
    does the manual state it is supported? Is there any other way using just
    the TestStand steps to order a database recordset on one or more fields?
    Any help would be appreciated.
    Grrrrr....
    Bob Rafuse
    Etec Inc.

    > Bob -
    > The database step types do not do anything special to the SQL command
    > that you give it. The step just passes the command to the ADO
    > provider. I tried a simple query using the step types with the
    > following command,
    >
    > "SELECT UUT_RESULT.* FROM UUT_RESULT WHERE ([UUT_SERIAL_NUMBER] =
    > 12345) ORDER BY [EXECUTION_TIME] ASC"
    >
    > and this return the expected results and the record count parameter
    > was as expected. I tried this on TS 1.0.2 and TS 2.0 with MS Access
    > 2000 and MS SQL Server 7.0. I do not have MS SQL Server 2000 at this
    > time.
    >
    > It would be surprised if the step types are messing something up.
    I've been doing some experimenting over the past couple of days. Simple,
    one-table queries seem to handle the ORDER BY clause fine. Th
    ings seem to
    get messed up when I try multi-table queries with ORDER BY clause with the
    TestStand database steps. I get no errors but the returned record counts
    are always 0 with the ORDER BY and positive without the ORDER BY. The exact
    same queries work fine in Visual Basic/ADO and the SQL Server Query
    Analyzer.
    > Questions:
    > 1. Have you verified whether the data is actually returned even though
    > the record count is zero?
    Hmmm... yes data IS getting returned (at least on the two instances I just
    checked), but the record count is always zero. I was not proceeding with
    processing if the record count was 0.
    Still... I don't know how to loop through the recordset without knowing how
    many records there are an not eventually generate an error by passing EOF.
    Is there another way using the TestStand database steps to determine a) the
    number of records in the recordset or b) when I'm at EOF?
    > 2. Are you using any advanced options on the Opend SQL Statement step
    > type, specifically
    the cursor type set to forward only? Forward only
    > cursors do not allow for record counts.
    Everything on the Advanced tab of the Open SQL Statement step is set to "Use
    Default".
    Bob.

  • Strange SQL statement in my PL/SQL session

    Hi all,
    i found a very strange SQL statement in my session.
    SELECT 1
    FROM SYS.streams$_prepare_ddl p
    WHERE ( (p.global_flag = 1 AND :1 IS NULL)
    OR (p.global_flag = 0 AND p.usrid = :2)
    AND ROWNUM = 1;
    This statement is waiting latch wait event but consistent get higher and higher.
    This session seems didn't execute my PL/SQL's main logic and halt at this statement.
    And after 5 or 6 hours this session is error out with snapshot too old.
    Does anyone know what this statement doing? according to Metalink for create table and create user statement will trigger this statement. But why it takes so long?
    Looking forward for your advise...

    If you have a problem with latch events, then maybe this session or another session is doing a similar action quite often and using the latches.
    I would check for some part of you application that constantly tries to create tables and/or users. Maybe it is possible to change that logic. E.g. use global temp tables.
    Also post your database version. Did you migrate recently or is it a fresh install?
    @user594309: Think more before posting. And read up about bind variables.

  • This SQL statement always in Top Activity, with PX Deq Credit: send blkd

    Hi gurus,
    The following SQL statement is always among the Top Activity. I can see the details in Enerprise manager that it suffers from PX Deq Credit: send blkd
    This is the statement:
    SELECT S.Product, S.WH_CODE, S.RACK, S.BATCH, S.EXP_DATE, FLOOR(Qty_Beg) QtyBeg_B,
            ROUND(f_convert_qty(S.PRODUCT, Qty_Beg-FLOOR(Qty_Beg), P.UOM_K ), 0) QtyBeg_K,
            FLOOR(Qty_In) QtyIn_B, ROUND(f_convert_qty(S.PRODUCT, Qty_In-FLOOR(Qty_In), P.UOM_K), 0) QtyIn_K,
            FLOOR(Qty_Out) QtyOut_B, ROUND(f_convert_qty(S.PRODUCT, Qty_Out-FLOOR(Qty_Out), P.UOM_K ), 0) QtyOut_K,
            FLOOR(Qty_Adj) QtyAdj_B, ROUND(f_convert_qty(S.PRODUCT, Qty_Adj-FLOOR(Qty_Adj), P.UOM_K ), 0) QtyAdj_K,
            FLOOR(Qty_End) QtyEnd_B, ROUND(f_convert_qty(S.PRODUCT, Qty_End-FLOOR(Qty_End), P.UOM_K ), 0) QtyEnd_K,
            S.LOC_CODE
            FROM V_STOCK_DETAIL S
            JOIN PRODUCTS P ON P.PRODUCT = S.PRODUCT
            WHERE S.Product = :pProduct AND S.WH_CODE = :pWhCode AND S.LOC_CODE = :pLocCode;The statement is invoked by our front end (web based app) for a browse table displayed on a web page. The result can be 10 to 8000. It is used to display the current stock availability for a particular product in a particular warehouse. The stock availability it self is kept in a View : V_Stock_Detail
    These are the parameters relevant to the optimizer:
    SQL> show parameter user_dump_dest
    user_dump_dest                       string   /u01/app/oracle/admin/ITTDB/udump
    SQL> show parameter optimizer
    _optimizer_cost_based_transformation  string   OFF
    optimizer_dynamic_sampling           integer  2
    optimizer_features_enable            string   10.2.0.3
    optimizer_index_caching              integer  0
    optimizer_index_cost_adj             integer  100
    optimizer_mode                       string   ALL_ROWS
    optimizer_secure_view_merging        boolean  TRUE
    SQL> show parameter db_file_multi
    db_file_multiblock_read_count        integer  16
    SQL> show parameter db_block_size column sname format a20 column pname format a20
    db_block_size                        integer  8192Here is the output of EXPLAIN PLAN:
    SQL> explain plan for
    SELECT S.Product, S.WH_CODE, S.RACK, S.BATCH, S.EXP_DATE, FLOOR(Qty_Beg) QtyBeg_B,
        ROUND(f_convert_qty(S.PRODUCT, Qty_Beg-FLOOR(Qty_Beg), P.UOM_K ), 0) QtyBeg_K,
        FLOOR(Qty_In) QtyIn_B, ROUND(f_convert_qty(S.PRODUCT, Qty_In-FLOOR(Qty_In), P.UOM_K), 0) QtyIn_K,
        FLOOR(Qty_Out) QtyOut_B, ROUND(f_convert_qty(S.PRODUCT, Qty_Out-FLOOR(Qty_Out), P.UOM_K ), 0) QtyOut_K,
        FLOOR(Qty_Adj) QtyAdj_B, ROUND(f_convert_qty(S.PRODUCT, Qty_Adj-FLOOR(Qty_Adj), P.UOM_K ), 0) QtyAdj_K,
        FLOOR(Qty_End) QtyEnd_B, ROUND(f_convert_qty(S.PRODUCT, Qty_End-FLOOR(Qty_End), P.UOM_K ), 0) QtyEnd_K,
        S.LOC_CODE
        FROM V_STOCK_DETAIL S
        JOIN PRODUCTS P ON P.PRODUCT = S.PRODUCT
        WHERE S.Product = :pProduct AND S.WH_CODE = :pWhCode AND S.LOC_CODE = :pLocCode
    Explain complete.
    Elapsed: 00:00:00:31
    SQL> select * from table(dbms_xplan.display)
    PLAN_TABLE_OUTPUT
    Plan hash value: 3252950027
    | Id  | Operation                               | Name                | Rows  | Bytes | Cost (%CPU)| Time     |    TQ  |IN-OUT| PQ
    Distrib |
    |   0 | SELECT STATEMENT                        |                     |     1 |   169 |     6  (17)| 00:00:01 |        |      |
             |
    |   1 |  PX COORDINATOR                         |                     |       |       |            |          |        |      |
             |
    |   2 |   PX SEND QC (RANDOM)                   | :TQ10003            |     1 |   169 |     6  (17)| 00:00:01 |  Q1,03 | P->S | QC
    (RAND)  |
    |   3 |    HASH GROUP BY                        |                     |     1 |   169 |     6  (17)| 00:00:01 |  Q1,03 | PCWP |
             |
    |   4 |     PX RECEIVE                          |                     |     1 |   169 |     6  (17)| 00:00:01 |  Q1,03 | PCWP |
             |
    |   5 |      PX SEND HASH                       | :TQ10002            |     1 |   169 |     6  (17)| 00:00:01 |  Q1,02 | P->P | HA
    SH       |
    |   6 |       HASH GROUP BY                     |                     |     1 |   169 |     6  (17)| 00:00:01 |  Q1,02 | PCWP |
             |
    |   7 |        NESTED LOOPS OUTER               |                     |     1 |   169 |     5   (0)| 00:00:01 |  Q1,02 | PCWP |
             |
    |   8 |         MERGE JOIN CARTESIAN            |                     |     1 |   119 |     4   (0)| 00:00:01 |  Q1,02 | PCWP |
             |
    |   9 |          SORT JOIN                      |                     |       |       |            |          |  Q1,02 | PCWP |
             |
    |  10 |           NESTED LOOPS                  |                     |     1 |    49 |     4   (0)| 00:00:01 |  Q1,02 | PCWP |
             |
    |  11 |            BUFFER SORT                  |                     |       |       |            |          |  Q1,02 | PCWC |
             |
    |  12 |             PX RECEIVE                  |                     |       |       |            |          |  Q1,02 | PCWP |
             |
    |  13 |              PX SEND BROADCAST          | :TQ10000            |       |       |            |          |        | S->P | BR
    OADCAST  |
    |* 14 |               INDEX RANGE SCAN          | PRODUCTS_IDX2       |     1 |    25 |     2   (0)| 00:00:01 |        |      |
             |
    |  15 |            PX BLOCK ITERATOR            |                     |     1 |    24 |     2   (0)| 00:00:01 |  Q1,02 | PCWC |
             |
    |* 16 |             MAT_VIEW ACCESS FULL        | MV_CONVERT_UOM      |     1 |    24 |     2   (0)| 00:00:01 |  Q1,02 | PCWP |
             |
    |  17 |          BUFFER SORT                    |                     |     1 |    70 |     2   (0)| 00:00:01 |  Q1,02 | PCWP |
             |
    |  18 |           BUFFER SORT                   |                     |       |       |            |          |  Q1,02 | PCWC |
             |
    |  19 |            PX RECEIVE                   |                     |     1 |    70 |     4   (0)| 00:00:01 |  Q1,02 | PCWP |
             |
    |  20 |             PX SEND BROADCAST           | :TQ10001            |     1 |    70 |     4   (0)| 00:00:01 |        | S->P | BR
    OADCAST  |
    |* 21 |              TABLE ACCESS BY INDEX ROWID| STOCK               |     1 |    70 |     4   (0)| 00:00:01 |        |      |
             |
    |* 22 |               INDEX RANGE SCAN          | STOCK_PK            |     1 |       |     2   (0)| 00:00:01 |        |      |
             |
    |* 23 |         TABLE ACCESS BY INDEX ROWID     | MV_TRANS_STOCK      |     1 |    50 |     3   (0)| 00:00:01 |  Q1,02 | PCWP |
             |
    |* 24 |          INDEX RANGE SCAN               | MV_TRANS_STOCK_IDX1 |     1 |       |     2   (0)| 00:00:01 |  Q1,02 | PCWP |
             |
    Predicate Information (identified by operation id):
      14 - access("P"."PRODUCT"=:PPRODUCT)
      16 - filter("CON"."PRODUCT"=:PPRODUCT)
      21 - filter("STOCK"."LOC_CODE"=:PLOCCODE)
      22 - access("STOCK"."PRODUCT"=:PPRODUCT AND "STOCK"."WH_CODE"=:PWHCODE)
      23 - filter("STS"(+)='N')
      24 - access("PRODUCT"(+)=:PPRODUCT AND "WH_CODE"(+)=:PWHCODE AND "LOC_CODE"(+)=:PLOCCODE AND "RACK"(+)="STOCK"."RACK" AND
                  "BATCH"(+)="STOCK"."BATCH" AND "EXP_DATE"(+)="STOCK"."EXP_DATE")
    42 rows selected.
    Elapsed: 00:00:00:06Here is the output of SQL*Plus AUTOTRACE including the TIMING information:
    SQL> SELECT S.Product, S.WH_CODE, S.RACK, S.BATCH, S.EXP_DATE, FLOOR(Qty_Beg) QtyBeg_B,
        ROUND(f_convert_qty(S.PRODUCT, Qty_Beg-FLOOR(Qty_Beg), P.UOM_K ), 0) QtyBeg_K,
        FLOOR(Qty_In) QtyIn_B, ROUND(f_convert_qty(S.PRODUCT, Qty_In-FLOOR(Qty_In), P.UOM_K), 0) QtyIn_K,
        FLOOR(Qty_Out) QtyOut_B, ROUND(f_convert_qty(S.PRODUCT, Qty_Out-FLOOR(Qty_Out), P.UOM_K ), 0) QtyOut_K,
        FLOOR(Qty_Adj) QtyAdj_B, ROUND(f_convert_qty(S.PRODUCT, Qty_Adj-FLOOR(Qty_Adj), P.UOM_K ), 0) QtyAdj_K,
        FLOOR(Qty_End) QtyEnd_B, ROUND(f_convert_qty(S.PRODUCT, Qty_End-FLOOR(Qty_End), P.UOM_K ), 0) QtyEnd_K,
        S.LOC_CODE
        FROM V_STOCK_DETAIL S
        JOIN PRODUCTS P ON P.PRODUCT = S.PRODUCT
        WHERE S.Product = :pProduct AND S.WH_CODE = :pWhCode AND S.LOC_CODE = :pLocCode
    Execution Plan
       0      SELECT STATEMENT Optimizer Mode=ALL_ROWS   1   169   6
       1    0   PX COORDINATOR
       2    1     PX SEND QC (RANDOM) SYS.:TQ10003 1   169   6   :Q1003  P->S   QC (RANDOM)
       3    2       HASH GROUP BY   1   169   6   :Q1003  PCWP
       4    3         PX RECEIVE   1   169   6   :Q1003  PCWP
       5    4           PX SEND HASH SYS.:TQ10002 1   169   6   :Q1002  P->P   HASH
       6    5             HASH GROUP BY   1   169   6   :Q1002  PCWP
       7    6               NESTED LOOPS OUTER   1   169   5   :Q1002  PCWP
       8    7                 MERGE JOIN CARTESIAN   1   119   4   :Q1002  PCWP
       9    8                   SORT JOIN          :Q1002  PCWP
      10    9                     NESTED LOOPS   1   49   4   :Q1002  PCWP
      11   10                       BUFFER SORT          :Q1002  PCWC
      12   11                         PX RECEIVE          :Q1002  PCWP
      13   12                           PX SEND BROADCAST SYS.:TQ10000           S->P   BROADCAST
      14   13                             INDEX RANGE SCAN ITT_NEW.PRODUCTS_IDX2 1   25   2
      15   10                       PX BLOCK ITERATOR   1   24   2   :Q1002  PCWC
      16   15                         MAT_VIEW ACCESS FULL ITT_NEW.MV_CONVERT_UOM 1   24   2   :Q1002  PCWP
      17    8                   BUFFER SORT   1   70   2   :Q1002  PCWP
      18   17                     BUFFER SORT          :Q1002  PCWC
      19   18                       PX RECEIVE   1   70   4   :Q1002  PCWP
      20   19                         PX SEND BROADCAST SYS.:TQ10001 1   70   4      S->P   BROADCAST
      21   20                           TABLE ACCESS BY INDEX ROWID ITT_NEW.STOCK 1   70   4
      22   21                             INDEX RANGE SCAN ITT_NEW.STOCK_PK 1     2
      23    7                 TABLE ACCESS BY INDEX ROWID ITT_NEW.MV_TRANS_STOCK 1   50   3   :Q1002  PCWP
      24   23                   INDEX RANGE SCAN ITT_NEW.MV_TRANS_STOCK_IDX1 1     2   :Q1002  PCWP
    Statistics
            570  recursive calls
              0  physical write total IO requests
              0  physical write total multi block requests
              0  physical write total bytes
              0  physical writes direct temporary tablespace
              0  java session heap live size max
              0  java session heap object count
              0  java session heap object count max
              0  java session heap collected count
              0  java session heap collected bytes
             83  rows processed
    Elapsed: 00:00:03:24
    SQL> disconnect
    Commit complete
    Disconnected from Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - 64bit Production
    With the Partitioning, OLAP and Data Mining optionsThe TKPROF output for this statement looks like the following:
    TKPROF: Release 10.2.0.3.0 - Production on Thu Apr 23 12:39:29 2009
    Copyright (c) 1982, 2005, Oracle.  All rights reserved.
    Trace file: ittdb_ora_9566_mytrace1.trc
    Sort options: default
    count    = number of times OCI procedure was executed
    cpu      = cpu time in seconds executing
    elapsed  = elapsed time in seconds executing
    disk     = number of physical reads of buffers from disk
    query    = number of buffers gotten for consistent read
    current  = number of buffers gotten in current mode (usually for update)
    rows     = number of rows processed by the fetch or execute call
    SELECT S.Product, S.WH_CODE, S.RACK, S.BATCH, S.EXP_DATE, FLOOR(Qty_Beg) QtyBeg_B,
        ROUND(f_convert_qty(S.PRODUCT, Qty_Beg-FLOOR(Qty_Beg), P.UOM_K ), 0) QtyBeg_K,
        FLOOR(Qty_In) QtyIn_B, ROUND(f_convert_qty(S.PRODUCT, Qty_In-FLOOR(Qty_In), P.UOM_K), 0) QtyIn_K,
        FLOOR(Qty_Out) QtyOut_B, ROUND(f_convert_qty(S.PRODUCT, Qty_Out-FLOOR(Qty_Out), P.UOM_K ), 0) QtyOut_K,
        FLOOR(Qty_Adj) QtyAdj_B, ROUND(f_convert_qty(S.PRODUCT, Qty_Adj-FLOOR(Qty_Adj), P.UOM_K ), 0) QtyAdj_K,
        FLOOR(Qty_End) QtyEnd_B, ROUND(f_convert_qty(S.PRODUCT, Qty_End-FLOOR(Qty_End), P.UOM_K ), 0) QtyEnd_K,
        S.LOC_CODE
        FROM V_STOCK_DETAIL S
        JOIN PRODUCTS P ON P.PRODUCT = S.PRODUCT
        WHERE S.Product = :pProduct AND S.WH_CODE = :pWhCode AND S.LOC_CODE = :pLocCode
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        1      0.00       0.00          0          0          0           0
    Execute      1      0.04       0.12          0         10          4           0
    Fetch       43      0.05       2.02          0         73          0          83
    total       45      0.10       2.15          0         83          4          83
    Misses in library cache during parse: 1
    Misses in library cache during execute: 1
    Optimizer mode: ALL_ROWS
    Parsing user id: 164 
    Rows     Row Source Operation
         83  PX COORDINATOR  (cr=83 pr=0 pw=0 time=2086576 us)
          0   PX SEND QC (RANDOM) :TQ10003 (cr=0 pr=0 pw=0 time=0 us)
          0    HASH GROUP BY (cr=0 pr=0 pw=0 time=0 us)
          0     PX RECEIVE  (cr=0 pr=0 pw=0 time=0 us)
          0      PX SEND HASH :TQ10002 (cr=0 pr=0 pw=0 time=0 us)
          0       HASH GROUP BY (cr=0 pr=0 pw=0 time=0 us)
          0        NESTED LOOPS OUTER (cr=0 pr=0 pw=0 time=0 us)
          0         MERGE JOIN CARTESIAN (cr=0 pr=0 pw=0 time=0 us)
          0          SORT JOIN (cr=0 pr=0 pw=0 time=0 us)
          0           NESTED LOOPS  (cr=0 pr=0 pw=0 time=0 us)
          0            BUFFER SORT (cr=0 pr=0 pw=0 time=0 us)
          0             PX RECEIVE  (cr=0 pr=0 pw=0 time=0 us)
          0              PX SEND BROADCAST :TQ10000 (cr=0 pr=0 pw=0 time=0 us)
          1               INDEX RANGE SCAN PRODUCTS_IDX2 (cr=2 pr=0 pw=0 time=62 us)(object id 135097)
          0            PX BLOCK ITERATOR (cr=0 pr=0 pw=0 time=0 us)
          0             MAT_VIEW ACCESS FULL MV_CONVERT_UOM (cr=0 pr=0 pw=0 time=0 us)
          0          BUFFER SORT (cr=0 pr=0 pw=0 time=0 us)
          0           BUFFER SORT (cr=0 pr=0 pw=0 time=0 us)
          0            PX RECEIVE  (cr=0 pr=0 pw=0 time=0 us)
          0             PX SEND BROADCAST :TQ10001 (cr=0 pr=0 pw=0 time=0 us)
         83              TABLE ACCESS BY INDEX ROWID STOCK (cr=78 pr=0 pw=0 time=1635 us)
         83               INDEX RANGE SCAN STOCK_PK (cr=4 pr=0 pw=0 time=458 us)(object id 135252)
          0         TABLE ACCESS BY INDEX ROWID MV_TRANS_STOCK (cr=0 pr=0 pw=0 time=0 us)
          0          INDEX RANGE SCAN MV_TRANS_STOCK_IDX1 (cr=0 pr=0 pw=0 time=0 us)(object id 143537)
    Elapsed times include waiting on following events:
      Event waited on                             Times   Max. Wait  Total Waited
      ----------------------------------------   Waited  ----------  ------------
      PX Deq: Join ACK                               17        0.00          0.00
      PX qref latch                                   2        0.00          0.00
      PX Deq Credit: send blkd                       72        1.95          2.00
      PX Deq: Parse Reply                            26        0.01          0.01
      SQL*Net message to client                      43        0.00          0.00
      PX Deq: Execute Reply                          19        0.00          0.01
      SQL*Net message from client                    43        0.00          0.04
      PX Deq: Signal ACK                             12        0.00          0.00
      enq: PS - contention                            1        0.00          0.00
    ********************************************************************************The DBMS_XPLAN.DISPLAY_CURSOR output:
    SQL> select * from table(dbms_xplan.display_cursor(null, null, 'ALLSTATS LAST'))
    PLAN_TABLE_OUTPUT
    SQL_ID  402b8st7vt6ku, child number 2
    SELECT /*+ gather_plan_statistics */          S.Product, S.WH_CODE, S.RACK, S.BATCH, S.EXP_DATE, FLOOR(Qty_Beg) QtyBeg_B,
    ROUND(f_convert_qty(S.PRODUCT, Qty_Beg-FLOOR(Qty_Beg), P.UOM_K ), 0) QtyBeg_K,      FLOOR(Qty_In) QtyIn_B, ROUND(f_convert_qty(S.P
    RODUCT,
    Qty_In-FLOOR(Qty_In), P.UOM_K), 0) QtyIn_K,      FLOOR(Qty_Out) QtyOut_B, ROUND(f_convert_qty(S.PRODUCT, Qty_Out-FLOOR(Qty_Out), P
    .UOM_K ),
    0) QtyOut_K,      FLOOR(Qty_Adj) QtyAdj_B, ROUND(f_convert_qty(S.PRODUCT, Qty_Adj-FLOOR(Qty_Adj), P.UOM_K ), 0) QtyAdj_K,
    FLOOR(Qty_End) QtyEnd_B, ROUND(f_convert_qty(S.PRODUCT, Qty_End-FLOOR(Qty_End), P.UOM_K ), 0) QtyEnd_K,      S.LOC_CODE      FROM
    V_STOCK_DETAIL S      JOIN PRODUCTS P ON P.PRODUCT = S.PRODUCT      WHERE S.Product = :pProduct AND S.WH_CODE = :pWhCode AND S.LOC
    _CODE =
    :pLocCode
    Plan hash value: 3252950027
    | Id  | Operation                               | Name                | Starts | E-Rows | A-Rows |   A-Time   | Buffers |  OMem |
    1Mem | Used-Mem |
    |   1 |  PX COORDINATOR                         |                     |      1 |        |     83 |00:00:02.25 |      83 |       |
          |          |
    |   2 |   PX SEND QC (RANDOM)                   | :TQ10003            |      0 |     21 |      0 |00:00:00.01 |       0 |       |
          |          |
    |   3 |    HASH GROUP BY                        |                     |      0 |     21 |      0 |00:00:00.01 |       0 |       |
          |          |
    |   4 |     PX RECEIVE                          |                     |      0 |     21 |      0 |00:00:00.01 |       0 |       |
          |          |
    |   5 |      PX SEND HASH                       | :TQ10002            |      0 |     21 |      0 |00:00:00.01 |       0 |       |
          |          |
    |   6 |       HASH GROUP BY                     |                     |      0 |     21 |      0 |00:00:00.01 |       0 |       |
          |          |
    |   7 |        NESTED LOOPS OUTER               |                     |      0 |     21 |      0 |00:00:00.01 |       0 |       |
          |          |
    |   8 |         MERGE JOIN CARTESIAN            |                     |      0 |     21 |      0 |00:00:00.01 |       0 |       |
          |          |
    |   9 |          SORT JOIN                      |                     |      0 |        |      0 |00:00:00.01 |       0 | 73728 |
    73728 |          |
    |  10 |           NESTED LOOPS                  |                     |      0 |      1 |      0 |00:00:00.01 |       0 |       |
          |          |
    |  11 |            BUFFER SORT                  |                     |      0 |        |      0 |00:00:00.01 |       0 | 73728 |
    73728 |          |
    |  12 |             PX RECEIVE                  |                     |      0 |        |      0 |00:00:00.01 |       0 |       |
          |          |
    |  13 |              PX SEND BROADCAST          | :TQ10000            |      0 |        |      0 |00:00:00.01 |       0 |       |
          |          |
    |* 14 |               INDEX RANGE SCAN          | PRODUCTS_IDX2       |      1 |      1 |      1 |00:00:00.01 |       2 |       |
          |          |
    |  15 |            PX BLOCK ITERATOR            |                     |      0 |      1 |      0 |00:00:00.01 |       0 |       |
          |          |
    |* 16 |             MAT_VIEW ACCESS FULL        | MV_CONVERT_UOM      |      0 |      1 |      0 |00:00:00.01 |       0 |       |
          |          |
    |  17 |          BUFFER SORT                    |                     |      0 |     21 |      0 |00:00:00.01 |       0 | 73728 |
    73728 |          |
    |  18 |           BUFFER SORT                   |                     |      0 |        |      0 |00:00:00.01 |       0 | 73728 |
    73728 |          |
    |  19 |            PX RECEIVE                   |                     |      0 |     21 |      0 |00:00:00.01 |       0 |       |
          |          |
    |  20 |             PX SEND BROADCAST           | :TQ10001            |      0 |     21 |      0 |00:00:00.01 |       0 |       |
          |          |
    |* 21 |              TABLE ACCESS BY INDEX ROWID| STOCK               |      1 |     21 |     83 |00:00:00.01 |      78 |       |
          |          |
    |* 22 |               INDEX RANGE SCAN          | STOCK_PK            |      1 |     91 |     83 |00:00:00.01 |       4 |       |
          |          |
    |* 23 |         TABLE ACCESS BY INDEX ROWID     | MV_TRANS_STOCK      |      0 |      1 |      0 |00:00:00.01 |       0 |       |
          |          |
    |* 24 |          INDEX RANGE SCAN               | MV_TRANS_STOCK_IDX1 |      0 |      1 |      0 |00:00:00.01 |       0 |       |
          |          |
    Predicate Information (identified by operation id):
      14 - access("P"."PRODUCT"=:PPRODUCT)
      16 - access(:Z>=:Z AND :Z<=:Z)
           filter("CON"."PRODUCT"=:PPRODUCT)
      21 - filter("STOCK"."LOC_CODE"=:PLOCCODE)
      22 - access("STOCK"."PRODUCT"=:PPRODUCT AND "STOCK"."WH_CODE"=:PWHCODE)
      23 - filter("STS"='N')
      24 - access("PRODUCT"=:PPRODUCT AND "WH_CODE"=:PWHCODE AND "LOC_CODE"=:PLOCCODE AND "RACK"="STOCK"."RACK" AND "BATCH"="STOCK"."B
    ATCH" AND
                  "EXP_DATE"="STOCK"."EXP_DATE")
    53 rows selected.
    Elapsed: 00:00:00:12I'm looking forward for suggestions how to improve the performance of this statement.
    Thank you very much,
    xtanto

    xtanto wrote:
    Hi sir,
    How to prevent the query from doing parallel query ?
    Because as you see actually I am not issuing any Parallel hints in the query.
    Thank you,
    xtantoKristanto,
    there are a couple of points to consider:
    1. Your SQL*Plus version seems to be outdated. Please use a SQL*Plus version that corresponds to your database version. E.g. the AUTOTRACE output is odd.
    2. I would suggest to repeat your exercise using serial execution (the plan, the autotrace, the tracing). You can disable parallel queries by issuing this in your session:
    ALTER SESSION DISABLE PARALLEL QUERY;
    This way the output of the tools is much more meaningful, however you might get a different execution plan, therefore the results might not be representative for your parallel execution.
    3. The function calls might pose a problem. If they are, one possible damage limitation has been provided by hoek. Even better would be then to replace the PL/SQL function with equivalent plain SQL. However since you say that it generates not too many rows it might not harm here too much. You can check the impact of the functions by running a similar query but omitting the function calls.
    4. The parallel execution plan contains a MERGE JOIN CARTESIAN operation which could be an issue if the estimates of the optimizer are incorrect. If the serial execution still uses this operation the TKPROF and DBMS_XPLAN.DISPLAY_CURSOR output will reveal whether this is a problem or not.
    5. The execution of the statement seems to take on 2-3 seconds in your tests. Is this in the right ballpark? If yes, why should this statement then be problematic? How often does it get executed?
    6. The statement uses bind variables, so you might have executions that use different execution plans depending on the bind values passed when the statement got optimized. You can use DBMS_XPLAN.DISPLAY_CURSOR using NULL as "child_number" parameter or DBMS_XPLAN.DISPLAY_AWR (if you have a AWR license) to check if you have multiple execution plans for the statement. Please note that older versions might have already been aged out of the shared pool, so the AWR repository might be a more reliable source (but only if the statement has been sampled).
    7. You have disabled cost based transformations: "_optimizer_cost_based_transformation" = OFF. Why?
    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/

  • Reg Balance forward

    Hi All,
    My current client has a custom program which will clear all customer open items and posts the balance as a transaction with specific document type. (The client calls this as balance forward as they are forwarding the balance). This balance is forwarded to another custom module kind of thing where they generate a customer statement which has details like how much the owe and the customer owes them. Based on this, they review the customer account and decide whether to pay him or not.
    My question is, is there a standard program or report which will clear all open items and post the balance. Or any other standard SAP way to do this instead of using custom program?
    Please respond with your thoughts and solutions as this is very important for me. I need to come up with a solution for this.
    Thank you for your time and help.
    Regards,
    Satya

    Thanks for the quick response.
    I agree with you that it is not actual balance forward process. Since they are forwarding the balance they call it as balance forward.
    Carrying the balance to new fiscal year is a seperate process for the client which is not included in this process what i explianed now. This process is mainly for specific type of customers where you can see all payments to customers and also collections from customers.
    You said they can use standard reports to see how much they have to pay to customer. Any idea what these reports are?
    At the time of payments, they modify the payment amount if necessary. I think this can be achieved by SAP Partial payment.
    I guess this whole custom process the client is having can be achieved in bit and pieces by standard SAP but do not know how?
    It would be really great if anyone can throw some light on it.
    Regards,
    Satya

  • SQL Statement needed for Query Generator

    Dear Experts,
    My view has the following three columns.
    1, Start Date
    2. End Date
    3. Balance.
    I need an SQL statement to write in query generator, which has to check if EndDate is less than the Current date and balance is above zero. If so, it assumes the last date of the job is already over, outstanding materials not yet been returned. Hence it has to return 'Pending'. If EndDate is greater than current date, it means final date for completion of the process is yet to come. So the task is in progress, hence it has to return 'Progress'. If the balance is Zero, all materials connected with the task have been received either as a FG or as Raw Materials. So it has to return, 'Completed'. I need a singe SQL Statement for this.
    Please help me.
    Thanks in advance.
    Regards
    Anand

    Dear Anand,
    Try this one:
    CASE balance WHEN 0 THEN 'Completed' ELSE CASE WHEN DATEDIFF(DD, EndDate, GetDate()) >= 0 THEN 'Progress' ELSE 'Pending' END END
    I have assumed you don't have negative balance.  It that is not true, give me the complete case.
    Thanks,
    Gordon
    Thanks,
    Gordon

  • Trouble with SQL Statements

    Hello all that can help,
    i am programming in Ready to Program to connect to a VideoShop database using SQL statements.
    I am having trouble when using single and double inverted commas. eg vs.updateRentTable ("DELETE FROM RentTable WHERE CustId=);
    but instead of specifiying the CustId i want to make it a variable id so that i can delete any name i want according to their ID.
    also i am wondering if it is possible to write data from a database into a text file? is it possible to use Printwriter?
    Looking forward to your help,
    Manuking16

    Hi Manuking_16,
    Your question should be posted on a sql forum, not on a JDBC forum. Anyway. Just looking for answers, right?
    1) If your datatype is INT, you do not use either quotes " or single quotes in your SQL statement
    DELETE FROM RentTable WHERE CustId= 12345.
    To build the SQL String in JAVA just write:
    {code}String sqlStatement = "DELETE FROM RentTable WHERE CustId = " + custID; // custID will be casted to String.{code}
    2) Use preparedStatement
    {code}PreparedStatement pStm = conn.prepareStatement(�DELETE FROM RentTable WHERE CustId = ?");
    pStm.setInt(1, customerID);
    int numberOfDeletedLines = pStm.execute();3) If you want to enter the real name to do the deletion
    DELETE FROM RentTable WHERE CustId IN (select custID FROM Customer WHERE name = "joe bob johnson")
        To build the SQL String in JAVA just write: String sqlStatement = "DELETE FROM RentTable WHERE CustId IN (select custID FROM Customer WHERE name = '" + sCustomerName + "' )"; // just copy & pasteHope I got your question right.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Sql statement generator for java.

    Is there a (api's ) tool which generates sql statements given a database table, which can be embeeded into the application.

    Dear Anand,
    Try this one:
    CASE balance WHEN 0 THEN 'Completed' ELSE CASE WHEN DATEDIFF(DD, EndDate, GetDate()) >= 0 THEN 'Progress' ELSE 'Pending' END END
    I have assumed you don't have negative balance.  It that is not true, give me the complete case.
    Thanks,
    Gordon
    Thanks,
    Gordon

  • Why has the sql statement been extucted two times in shell script?

    I tried to test rac load balance using the following shell script on suse 10 + oracle 10g rac.
    oracle@SZDB:~> more load_balance.sh
    #!/bin/bash
    for i in {1..20}
    do
    echo $i
    sqlplus -S system/oracle@ORA10G <<EOF
    select instance_name from v\$instance;
    EOF
    sleep 1
    done
    exit 0After execute shell script, I got the follow result.
    oracle@SZDB:~> ./load_balance.sh
    1
    INSTANCE_NAME
    ora10g2
    INSTANCE_NAME
    ora10g2
    2
    INSTANCE_NAME
    ora10g1
    INSTANCE_NAME
    ora10g1
    3
    INSTANCE_NAME
    ora10g1
    INSTANCE_NAME
    ora10g1Seem the sql statement has been executed two times in each loop. If you feel free please help to have a look. Thanks in advance.
    Robinson

    You can end a SQL command in one of three ways:
    * with a semicolon (;)
    * with a slash (/) on a line by itself
    * with a blank line
    A semicolon (;) tells SQL*Plus that you want to run the current command that was entered. SQL*Plus processes the command and also stores the command in the SQL buffer.
    A blank line in a SQL statement or script tells SQL*Plus that you have finished entering the command, but do not want to run it yet, but it's stored the command on SQL Buffer.
    A slash (/) on a line by itself tells SQL*Plus that you wish to run the command stored on SQL buffer.

  • Failed to post data to database during "Update": SQL Statement

    Hi,
    I'm getting this error while trying to update a VO via BCBrowser or UI.
    Failed to post data to database during "Update": SQL Statement
    This is a simple & straight forward default VO created on Entity Object (Database Table)
    On the same table & with same DB credentials, I could successfully update the record.
    Any Guess, on what went Wrong??
    Thanks in Advance for any help.
    p.s Jdev 11.1.1.6
    Log:
    oracle.jbo.DMLException: JBO-26041: Failed to post data to database during "Update": SQL Statement "BEGIN UPDATE CAR CarEO SET SEL_ITEM=:1 WHERE TXN_NO=:2 AND LOGID=:3 AND SEQNO=:4 RETURNING DELIVERY_MODE, CERTIFICATION_REQ, SOFT_COPY_IND, SELITEM INTO :5, :6, :7, :8; END;".
      at oracle.jbo.server.OracleSQLBuilderImpl.doEntityDML(OracleSQLBuilderImpl.java:583)
      at oracle.jbo.server.EntityImpl.doDML(EntityImpl.java:8575)
      at oracle.jbo.server.EntityImpl.postChanges(EntityImpl.java:6816)
      at oracle.jbo.server.DBTransactionImpl.doPostTransactionListeners(DBTransactionImpl.java:3290)
      at oracle.jbo.server.DBTransactionImpl.postChanges(DBTransactionImpl.java:3093)
      at oracle.jbo.server.DBTransactionImpl.commitInternal(DBTransactionImpl.java:2097)
      at oracle.jbo.server.DBTransactionImpl.commit(DBTransactionImpl.java:2378)
      at oracle.adf.model.bc4j.DCJboDataControl.commitTransaction(DCJboDataControl.java:1615)
      at oracle.adf.model.binding.DCDataControl.callCommitTransaction(DCDataControl.java:1417)
      at oracle.jbo.uicli.binding.JUCtrlActionBinding.doIt(JUCtrlActionBinding.java:1437)
      at oracle.adf.model.binding.DCDataControl.invokeOperation(DCDataControl.java:2150)
      at oracle.jbo.uicli.binding.JUCtrlActionBinding.invoke(JUCtrlActionBinding.java:740)
      at oracle.jbo.uicli.jui.JUActionBinding.actionPerformed(JUActionBinding.java:193)
      at oracle.jbo.uicli.controls.JUNavigationBar.doAction(JUNavigationBar.java:412)
      at oracle.jbo.jbotester.NavigationBar.doAction(NavigationBar.java:111)
      at oracle.jbo.uicli.controls.JUNavigationBar$NavButton.actionPerformed(JUNavigationBar.java:118)
      at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
      at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
      at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
      at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
      at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
      at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:272)
      at java.awt.Component.processMouseEvent(Component.java:6289)
      at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
      at java.awt.Component.processEvent(Component.java:6054)
      at java.awt.Container.processEvent(Container.java:2041)
      at java.awt.Component.dispatchEventImpl(Component.java:4652)
      at java.awt.Container.dispatchEventImpl(Container.java:2099)
      at java.awt.Component.dispatchEvent(Component.java:4482)
      at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
      at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
      at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
      at java.awt.Container.dispatchEventImpl(Container.java:2085)
      at java.awt.Window.dispatchEventImpl(Window.java:2478)
      at java.awt.Component.dispatchEvent(Component.java:4482)
      at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:644)
      at java.awt.EventQueue.access$000(EventQueue.java:85)
      at java.awt.EventQueue$1.run(EventQueue.java:603)
      at java.awt.EventQueue$1.run(EventQueue.java:601)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
      at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
      at java.awt.EventQueue$2.run(EventQueue.java:617)
      at java.awt.EventQueue$2.run(EventQueue.java:615)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
      at java.awt.EventQueue.dispatchEvent(EventQueue.java:614)
      at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
      at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
      at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
      at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
      at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
    Caused by: java.sql.SQLException: Invalid column type
      at oracle.jdbc.driver.OracleCallableStatement.registerOutParameterInternal(OracleCallableStatement.java:150)
      at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:399)
      at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:581)
      at oracle.jdbc.driver.OracleCallableStatementWrapper.registerOutParameter(OracleCallableStatementWrapper.java:1765)
      at oracle.jbo.server.OracleSQLBuilderImpl.bindUpdateStatement(OracleSQLBuilderImpl.java:2243)
      at oracle.jbo.server.EntityImpl.bindDMLStatement(EntityImpl.java:10524)
      at oracle.jbo.server.OracleSQLBuilderImpl.doEntityDML(OracleSQLBuilderImpl.java:412)
      ... 52 more

    The issue is resolved now.
    new Columns added to the Database table, after creating Entity Object. These latest changes were not picked up in Entity Object.
    I found this difference after comparison of entity object with DB Table.
    And when I added those new columns to EO & VO, I'm not getting this error anymore.
    Thanks to all who tried to help

  • How can i use one SQL statement to solve problem?

    How can i use one SQL statement to solve the question below?
    For a Table named A, there is a column named F(char type).
    Now select all the records where F like '%00' and update their F value to '%01'
    Just one SQL statement.Do not use PL/SQL block.
    How to do that?
    Thanks.

    What is the data volume for this table?
    Do you expect lots of rows to have '%00' as their value?
    Following two statements come to mind. Other experts would be able to provide better alternatives:
    If you have index on SUBSTR(f, 2):
    UPDATE A
    SET    f = SUBSTR(f,
                      1,
                      length(f) - 2) || '01'
    WHERE  substr(f,
                  -2) = '00';If most of the rows have pattern '%00':
    UPDATE A
    SET    f = SUBSTR(f,
                      1,
                      length(f) - 2) ||
               DECODE(SUBSTR(f,
                             -2),
                      '00',
                      '01',
                      SUBSTR(f,
                             -2));

  • How do I use SQL statements to perform calculations with form fields????

    Please help!!! I don't know how to use a SQL statement within my APEX form......
    My form is below. The user will enter the values in the form. Click on Submit. Then we need to run a SQL select statement with those values.
    Our form looks like this:
    Start_Date ____________
    Per_Period ____________
    Period ____________
    [Submit Button]
    The user will enter these 3 values in the form.
    This is an example of an user providing the values:
    Start_Date 03/14/08_______
    Per_Period $200.00________
    Period 4____________
    [Submit Button]
    Then they will click the Submit Button.
    The SQL statement (BELOW) returns output based on the users selections:
    START_DATE PER_PERIOD PERIOD
    14-MAR-2008 00:00 200 Week 1 of 4
    21-MAR-2008 00:00 200 Week 2 of 4
    28-MAR-2008 00:00 200 Week 3 of 4
    04-APR-2008 00:00 200 Week 4 of 4
    Total 800
    This is the full text of the SQL that makes the output above:
    with criteria as (select to_date('03/14/08', 'mm/dd/rr') as start_date,
    4 as periods,
    'Week' as period,
    200 per_period from dual),
    periods as (select 'Week' period, 7 days, 0 months from dual
    union all select 'BiWeek', 14, 0 from dual
    union all select 'Month', 0, 1 from dual
    union all select 'ByMonth', 0, 2 from dual
    union all select 'Quarter', 0, 3 from dual
    union all select 'Year', 0 , 12 from dual
    t1 as (
    select add_months(start_date,months*(level-1))+days*(level-1) start_date,
    per_period,
    c.period||' '||level||' of '||c.periods period
    from criteria c join periods p on c.period = p.period
    connect by level <= periods)
    select case grouping(start_date)
    when 1 then 'Total'
    else to_char(start_date)
    end start_date,
    sum(per_period) per_period,
    period
    from t1
    group by rollup ((start_date, period))
    THANKS VERY MUCH!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    You're just doing a parameterized report, where the input fields are your parameters.
    Check out the Advanced Tutorial titled Parameterized Report here:
    http://download.oracle.com/docs/cd/E10513_01/doc/appdev.310/e10497/rprt_query.htm#BGBEEBJA
    Good luck,
    Stew

Maybe you are looking for