SQL Statement / Count & Percentage

Hello All,
Below is the SQL statement that I'm using with an MS Access database. Now, I'm looking for an SQL statement that will get the same results using an SQL Compact database.
Here is what I am using with MS Access that works great:
queryString = "SELECT DStatus, Count(DStatus) As CountOfSummaryItem, (Count(*)/(Select count(*) FROM tbl_Records_DR)) as Percentage From tbl_Records_DR GROUP BY DStatus Order BY Count(DStatus) DESC;"
Results are something like this out of a total 50 records in the database:
Status   -   Count  -   Percentage
Broken   -   5     -   10%
Stopped -   10   -   20%
Return   -   20   -   40%
Closed   -   15   -   30%
Thanks,
ADawn
ADawn

SQL Server Compact has limited support for subqueries. I would suggest:
SELECT DStatus, Count(*) FROM tbl_Records_DR GROUP BY DStatus
to get the record count per "DStatus", and load the results on a generic List<> object, where you would do the math in code, or else, get first the total record count into a int variable, executing a scalar command with the following instruction
(C#):
SqlCeCommand totalCountCommand = new SqlCeCommand("SELECT Count(*) FROM tbl_Records_DR", myConnection);int i = (int)totalCountCommand.ExecuteScalar();
...and then use that value on the following instruction, either using string concatenation or a command parameter to divide each value fot the total count...
SqlCeCommand rowCountCommand = new SqlCeCommand("SELECT DStatus, Count(*), Count(*)/" + i.ToString() + " * 100 AS Percentage FROM tbl_Records_DR GROUP BY DStatus", myConnection);SqlCeDataReader r = rowCountCommand.ExecuteReader();
This is not tested code, it's just meant to give you an idea on how to get the result.
Alberto Silva Microsoft MVP - Device Application Development - http://msmvps.com/AlbertoSilva moving2u - R&D Manager - http://www.moving2u.pt

Similar Messages

  • The best way to do paging and get total rows count given a sql statement

    Hi,
    Just got a quick question.... what is the best way to do paging as well as the total rows count given by a sql statement.
    e.g. "select * from emp"
    1. I need to know the total row count for this statement.
    2. I also need to do a 10 rows per page....
    Is there a way to do it in a SINGLE statement for best performance?
    Thanks experts.

    Sounds more like a "formatting" problem...
    If Sql*plus is your reporting tool, check out the guide:
    http://download-west.oracle.com/docs/cd/B10501_01/server.920/a90842/toc.htm

  • SQL statement with LIMIT and total count?

    Hello,
    I would like to know if it is possible to execute a single SQL statement that will return me a subset of data (for pagination purposes) that not only includes the subset of data for the page but the count of all available data. Can this be done so as to not take up the cpu and time it takes to essentially run two queries? One to get the subset and one to get the count? I think simply doing a subselect is not going to give me what I want in that we actually query twice.
    There may be no way to do this other than that, but I wanted to check with the gurus here first. :)
    Thanks,
    Mark

    select *
    from (
    select i.*,
    row_number() over(order by i) rn, -- used for
    pagination
    count(*) over(partition by 1) cnt  -- total count
    of rows found for this search
    from mytable
    where < PUT ALL LIMITING (i.e., "search") CONDITIONS
    HERE >
    where rn between 41 and 50 -- pagination clauseNice one
    BUT of course it adds additional row in execution plan and takes additional time and CPU :)
    I assume that it directly depends of course on returned result set and some other factors like available sort space but a simple test case on a table big which actually is 1.6 M rows like dba_source got following results:
    here is the first one returning also count(*)
    SQL> select *
      2  from (
      3    select i.*,
      4      row_number() over(order by owner, name, type) rn
      5  , -- used for pagination
      6      count(*) over(partition by 1) cnt  -- total count of rows found for this search
      7    from big i
      8    where owner like 'S%' and name like '%A%'
      9  )
    10  where rn between 41 and 45
    11  /
    OWNER                          NAME                           TYPE
          LINE
    TEXT
            RN        CNT
    SYS                            ANYDATA                        TYPE
            13
      STATIC FUNCTION ConvertVarchar(c IN VARCHAR) return AnyData,
            41     999744
    SYS                            ANYDATA                        TYPE
            11
      STATIC FUNCTION ConvertDate(dat IN DATE) return AnyData,
            42     999744
    SYS                            ANYDATA                        TYPE
             9
            43     999744
    SYS                            ANYDATA                        TYPE
             7
         They serve as explicit CAST functions from any type in the Oracle ORDBMS
            44     999744
    SYS                            ANYDATA                        TYPE
             6
         enable construction of the AnyData in its entirity with a single call.
            45     999744
    Elapsed: 00:00:41.02
    SQL> ed
    Wrote file afiedt.buf
      1  select n.name, m.value from v$statname n, v$mystat m
      2  where n.statistic# = m.statistic#
      3*   and (upper(name) like '%SORT%' or upper(name) like '%TEMP%')
    SQL> /
    NAME                                                                  VALUE
    physical reads direct temporary tablespace                            35446
    physical writes direct temporary tablespace                           17723
    RowCR attempts                                                            0
    SMON posted for dropping temp segment                                     0
    sorts (memory)                                                           36
    sorts (disk)                                                              1
    sorts (rows)                                                        1999596
    OTC commit optimization attempts                                          0
    8 rows selected.here is the second one returning only rows:
    SQL> ed
    Wrote file afiedt.buf
      1  select *
      2  from (
      3    select i.*,
      4      row_number() over(order by owner, name, type) rn
      5  --, -- used for pagination
      6  --    count(*) over(partition by 1) cnt  -- total count of rows found for this search
      7    from big i
      8    where owner like 'S%' and name like '%A%'
      9  )
    10* where rn between 41 and 45
    SQL> /
    OWNER                          NAME                           TYPE
          LINE
    TEXT
            RN
    SYS                            ANYDATA                        TYPE
            13
      STATIC FUNCTION ConvertVarchar(c IN VARCHAR) return AnyData,
            41
    SYS                            ANYDATA                        TYPE
            11
      STATIC FUNCTION ConvertDate(dat IN DATE) return AnyData,
            42
    SYS                            ANYDATA                        TYPE
             9
            43
    SYS                            ANYDATA                        TYPE
             7
         They serve as explicit CAST functions from any type in the Oracle ORDBMS
            44
    SYS                            ANYDATA                        TYPE
             6
         enable construction of the AnyData in its entirity with a single call.
            45
    Elapsed: 00:00:12.09
    SQL> select n.name, m.value from v$statname n, v$mystat m
      2  where n.statistic# = m.statistic#
      3    and (upper(name) like '%SORT%' or upper(name) like '%TEMP%')
      4  /
    NAME                                                                  VALUE
    physical reads direct temporary tablespace                                0
    physical writes direct temporary tablespace                               0
    RowCR attempts                                                            0
    SMON posted for dropping temp segment                                     0
    sorts (memory)                                                           10
    sorts (disk)                                                              0
    sorts (rows)                                                         999812
    OTC commit optimization attempts                                          0
    8 rows selected.So execution time 41 sec vs 12 sec
    sorts (rows) 1 999 596 vs 999 812
    physical reads/writes direct temporary tablespace 35446/17723 vs 0/0
    I assume that for a small overall returned row count it probably is OK, but for less restrictive search it can be quite deadly as before with two queries.
    Gints Plivna
    http://www.gplivna.eu

  • Getting A Count In One SQL Statement

    Since I don't know how to do what I'm about to ask, I would normally create a table (tbl1) with the main dataset I want and then create a second table (tbl2) with additional data I want, join the two and update tbl1 data with tbl2 data.
    However, I would like to know how to do this in one SQL statement. I somehow need to link the count sql with the main body..?
    So..I have to pull data by group id. Each group id can have a certain number of active members in it. I would like to use one SQL statement to pull the group id's and also, at the same time, give me a count of each group's active membership. Both the main and count statments in the below SQL include the emp_grps table which can obviously be linked so the right groups are updated..
    Not sure how to begin to reflect this in an SQL statement, so I'll just give you the wrong version to show what data elements I have. The following gives the total count by all group's in each groups individual record. Of course, as mentioned, all I want is that group's share of the membership in their individual record:
    select group_id,
    (select count(*)
    from elig elg
    join emp_grps eg
    on elg.group_id = eg.group_id
    where eg.rmc_code in ('CR')
    and elg.elig_start_date < sysdate
    and elg.elig_end_date > sysdate) mbr_count
    from odw.emp_grps eg
    where eg.rmc_code in ('1M')
    Output from this query:
    GROUP_ID MBR_COUNT
    A 10,000
    B 10,000
    C 10,000
    D 10,000
    What I want to see:
    GROUP_ID MBR_COUNT
    A 7,000
    B 1,000
    C 1,500
    D 500
    Thanks for any assistance..

    Hi,
    So you want one row for every distinct value of group_id, with a count that reflects just that group_id.
    That sound like a job for GROUP BY group_id and the aggregate COUNT function, like this:
    SELECT    eg.group_id
    ,       COUNT ( CASE
                      WHEN  eg.rmc_code  IN ('CR')
                    THEN  1
                  END
                )     AS mbr_count
    FROM        elig           elg
    JOIN       emp_grps      eg    ON   elg.group_id  = eg.group_id
    WHERE       eg.rmc_code             IN ('CR', '1M')
    AND       elg.elig_start_date < SYSDATE
    AND       elg.elig_end_date   > SYSDATE
    GROUP BY  eg.group_id
    HAVING       COUNT ( CASE
                      WHEN  eg.rmc_code  IN ('1M')
                    THEN  1
                  END
                ) > 1
    ORDER BY  eg.group_id
    ;It's unclear what you're trying to do with eg.rmc_code. I'm guessing you want to count the rows where it's one value ('CR'), but only display groups that also have another value ('1M').
    Of course, I can't say for sure without seeing your actual tables, or at least small test versions of them.
    Post CREATE TABLE and INSERT statements (relevant columns only) for all tables involved, and the resutls you want from that sample data (if it's not the results you already posted).
    Always say which version of Oracle you're using.

  • Can I write merge SQL statement having count(*)?

    Hi this is a followup question of my previous post. I tried to use a merge SQL statement to solve my problem but now I bump into another problem.
    Now I have a table where the field I need to update is a partial PK
    when using a merge SQL statement, I have to put a where clause that check if count(*) = 1 because of the PK constraint
    Where can I put the count(*) = 1 clause?
    Here are the details:
    I have two tables TA and TB, where TA contains the fields ID, FULLNAME, TYPE and TB contains the fields ID, FIRSTNAME
    I want to update the firstnames in TB to be the firstnames from TA where TB.ID = TA.ID and TA.TYPE = 'ABC'
    {ID, FIRSTNAME} are PKs but for the same ID, there can be more than 1 firstname.
    e.g.
    TA
    ID | FULLNAME | TYPE
    1 Caroline T ABC
    2 Mary C DEF
    3 Peter J ABC
    TB
    ID | FIRSTNAME
    1 Caroline
    1 Carol
    1 C,
    3 Peter
    I need to update TB with the new firstnames from TA where type is 'ABC' but only for those fields that have count(TB.ID) = 1
    when I try to run this SQL statement
    merge into TB B using TA A
    on (A.ID = B.ID and A.TYPE = 'ABC')
    when matched then update set B.FIRSTNAME = substr(A.FULLNAME, 1, instr(A.FULLNAME, ',') - 1)
    I got this error SQL Error: ORA-00001: unique constraint (TEST.PK_TB) violated
    which I believe is because I updated those fields say ID = 1, all with 'Caroline'
    that means I will have to add a clause having count(TB.ID) = 1
    How would you do it?
    Server is Oracle 11g
    Thank you!

    Hi,
    One way is to join ta and tb in the USING clause, and eliminate the duplicates there.
    MERGE INTO     tb     dst
    USING   (
             SELECT    ta.id
             ,           REGEXP_SUBSTR ( MIN (ta.fullname)
                                    , '^[^,]*'
                            )     AS firstname
             FROM      ta
             JOIN      tb  ON  ta.id     = tb.id
             WHERE     ta.type      = 'ABC'
             GROUP BY  ta.id
             HAVING    COUNT (*)     = 1
         )                   src
    ON     (scr.id      = dst.id)
    WHEN MATCHED THEN UPDATE
    SET     dst.firstname     = src.firstname
    ;If you'd care to post CREATE TABLE and INSERT statements for your sample data, then I could test this.
    I used REGEXP_SUBST instead of SUBSTR and INSTR to find the firstname, because I find it a little cleaner, and becuase it returns something even when there is no ',' in fullname, which I'm guessing is what you really want. (None of the fullnames in your sample data have ','s.) You could use SUBSTR and INSTR instead.

  • Select count(*) on sql statement returning zero when a matching row exists.

    Our account has an ANSI C application that checks for the existence a row on an Oracle table(s) by using the following SQL:
    int iCount = 0;
    EXEC SQL
    SELECT count(rownum) INTO :iCount
    FROM sys.all_tab_columns
    WHERE table_name IN
    (SELECT table_name FROM
    sys.all_synonyms
    WHERE upper(synonym_name) = upper(:szDestTable))
    AND upper(column_name) = upper(:szColumnName)
    AND owner = 'DBAUSER';
    The bind variables szDestTable and szColumnName are populated with values parsed from columns on another database table. This application is executed through out the day. Occasionally, the application will report a zero in the iCount when there should be a match. I have verified the szDestTable and szColumnName are populated with the correct values which would find a match and they are correct. To make matters even stranger, the application will parse the same input values and find a match (as it should). At some point during the day, and it can be at any time, the application will NOT find a match on the same file, same values. Every subsequent execution of this application will not find a match on the same values. Once the database is brought down and started up in the evening for its normal backups, the application will find a match again on the same values. This problem does not occur every day. I could be a week or a week and a half between incidents.
    I printed the contents of the sqlca.sqqlerrm.sqlerrmc field to a log file. The sqlca.sqlerrm.sqlerrmc field reported an ORA-1405 bind variable was null when the iCount was reporting a zero. When I compiled this application, I set the Proc*C flag to UNSAFE_NULLS=yes since there are other bind variable in the application that can be NULL and that is ok.
    The above SQL is compiled into the C application using the Proc*C compiler. It is compiled using the Oracle 11.2.0.2 libraries. The application is executed against an Oracle 11.2.0.2 database. The database and application are executed on an HP/Unix 11.31 platform.
    This problem did not start occurring until our account went from Oracle 10.2 to Oracle 11.2. Recently, I have changed the SQL to perform a “SELECT COUNT(rownum)” instead of the “SELECT COUNT(*)”. I compiled the application and executed the new application with the SELECT COUNT(rownum) against the same database where the same application with the SELECT COUNT(*) was failing to find a row that actually existed. The application with the SELECT COUNT(rownum) found the matching row as it should have. The new application has been executing in production for about 10 days now without any problems against ten various Oracle 11.2 databases.
    Why would SELECT COUNT(*) and SELECT COUNT(rownum) be any different?

    This forum is about C programming in general, and about using Studio C in particular.
    Your question is about Oracle database programming. You are more likely to find a helpful answer in a forum about database programming. Start here:
    https://forums.oracle.com/forums/category.jspa?categoryID=18

  • Two count(*) in sql statement

    hi viewers,
    I need the similar query in oracle for the following Informix query.
    select count(*),(select count(*) from table_name where col1=10) from table_name where col1=10;
    i have a solution also but the problem is, if that table has no rows then output is not 0,0
    select count(*),(select count(*) from table_name where col1=10) from table_name where col1=10 group by col1;
    thanks
    hari

    A little remark: the behavoiur you stick on is a default feature in Oracle:
    SQL> select count(*) from emp where deptno = 40;
      COUNT(*)
             0
    SQL> select count(*) from emp where deptno = 40 group by deptno;
    no rows selectedThese two queries work differ. It is described in Oracle documentation:
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions001.htm#i89203
    Oracle applies the aggregate functions to each group of rows and returns a single result row for each group.
    If you omit the GROUP BY clause, then Oracle applies aggregate functions in the select list to all the rows in the queried table or view
    As Alex pointed out, you should not include group by clause and should use count(*) instead of a subquery.
    Rgds.

  • 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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Produce report NOT based on a single sql statement

    I want to produce a tabular report based on a series of sql statments. Specifically, a report of managers that wil include counts of employees that are in other tables using differing criterias.
    Name Count Count
    using using
    criteria 1 criteria 2
    Manager1 35 242
    I would expect to write an anonymous pl/sql block with a driving cursor determining the managers to report on. Within that cursor, I would execute a number of other queries to derive the count for each of the two columns.
    I have tried creating a report region based on a sql statement, but that requires a single sql statement. I also tried creating a report region based on plsql, but it required an into statement of defined items. This option looks like it can provide multiple rows, but since it selected 'INTO' named fields, it only creates a report with the last row of data.
    I must be missing something. Any suggestions are greatly appreciated!!!

    If you want a wizard to create the form and report for you then yes you need to have a table. One thing that you can do is define a view that contains the data you need and define an Instead Of trigger on that view so the automatic fetch and dml will work but you can have the data stored into the different objects. basically the view and the trigger work as a router/dispatcher for the data.
    *edit*
    I should also add that you can write a pl/sql package which does the fetch and the dml operations with the form items as input. This is the solution I would typically use for any form that was not a simple CRUD form for a table. One thing to note is for the fetch I prefer to use out parameters for the form items so it requires the developer to map the item to the param in the app so it will show up when you are searching through the app. I highly discourage hiding item references inside of packaged code.
    Good Luck!
    Tyson
    Message was edited by: TysonJouglet

  • Sql statement in a table not accepting variable

    I have the following problem on 10.1.0.3.0 with varialbe in an execute immediate statement
    here is the code that I am using
    declare
    remote_data_link varchar2(25) := 'UDE_DATATRANSFER_LINK';
    FROM_SCHEMA VARCHAR2(40) := 'UDE_OLTP';
    l_last_process_date date := to_date(to_char(sysdate,'mm-dd-yyyy hh:mi:ss'),'mm-dd-yyyy hh:mi:ss') - 1;
    stmt varchar2(4000) := 'MERGE into applicant_adverseaction_info theTarget USING (select * from '||FROM_SCHEMA||'.applicant_adverseaction_info@'||remote_data_link||' where last_activity > :l_last_process_date ) theSource ON(theTarget.applicant_id = theSource.applicant_id) WHEN MATCHED THEN UPDATE SET theTarget.cb_used = theSource.cb_used, theTarget.cb_address = theSource.cb_address, theTarget.scoredmodel_id = theSource.scoredmodel_id, theTarget.last_activity = theSource.last_activity WHEN NOT MATCHED THEN INSERT(CB_USED, CB_ADDRESS, SCOREDMODEL_ID, APPLICANT_ID, LAST_ACTIVITY) values(theSource.cb_used, theSource.cb_address, theSource.scoredmodel_id, theSource.applicant_id, theSource.last_activity)';
    stmt2 varchar2(4000) := 'MERGE into edm_application theTarget USING (select * from '||from_schema||'.edm_application@'||remote_data_link||' where last_activity > :l_last_process_date) theSource ON (theTarget.edm_appl_id = theSource.edm_appl_id) WHEN MATCHED THEN UPDATE SET theTarget.APP_REF_KEY = theSource.APP_REF_KEY, theTarget.IMPORT_REF_KEY = theSource.IMPORT_REF_KEY, theTarget.LAST_ACTIVITY = theSource.LAST_ACTIVITY WHEN NOT MATCHED THEN INSERT (EDM_APPL_ID, APP_REF_KEY, IMPORT_REF_KEY, LAST_ACTIVITY) values(theSource.EDM_APPL_ID, theSource.APP_REF_KEY, theSource.IMPORT_REF_KEY, theSource.LAST_ACTIVITY)';
    v_error varchar2(4000);
    T_MERGE VARCHAR2(4000);
    stmt3 varchar2(4000);
    BEGIN
    select merge_sql
    INTO T_MERGE
    from transfertables
    where table_name= 'edm_application';
    remote_data_link:= 'UDE_DATATRANSFER_LINK';
    FROM_SCHEMA := 'UDE_OLTP';
    --DBMS_OUTPUT.PUT_LINE(SUBSTR(stmt2,1,200));
    --STMT2 := T_MERGE;
    dbms_output.put_line(from_schema||' '||remote_data_link||' '||l_last_process_date);
    EXECUTE IMMEDIATE stmt2 using l_last_process_date;
    --execute immediate stmt3 ;
    dbms_output.put_line(from_schema||' '||remote_data_link||' '||l_last_process_date);
    dbms_output.put_line(substr(stmt2,1,200));
    commit;
    EXCEPTION
    WHEN OTHERS THEN
    V_ERROR := SQLCODE||' '||SQLERRM;
    v_ERROR := V_ERROR ||' '||SUBSTR(stmt2,1,200);
    DBMS_OUTPUT.PUT_LINE(V_ERROR);
    --dbms_output.put_line(substr(stmt2,1,200));
    END;
    This works perfectly
    but if I change it to get the same statement in a db table
    declare
    remote_data_link varchar2(25) := 'UDE_DATATRANSFER_LINK';
    FROM_SCHEMA VARCHAR2(40) := 'UDE_OLTP';
    l_last_process_date date := to_date(to_char(sysdate,'mm-dd-yyyy hh:mi:ss'),'mm-dd-yyyy hh:mi:ss') - 1;
    stmt varchar2(4000) := 'MERGE into applicant_adverseaction_info theTarget USING (select * from '||FROM_SCHEMA||'.applicant_adverseaction_info@'||remote_data_link||' where last_activity > :l_last_process_date ) theSource ON(theTarget.applicant_id = theSource.applicant_id) WHEN MATCHED THEN UPDATE SET theTarget.cb_used = theSource.cb_used, theTarget.cb_address = theSource.cb_address, theTarget.scoredmodel_id = theSource.scoredmodel_id, theTarget.last_activity = theSource.last_activity WHEN NOT MATCHED THEN INSERT(CB_USED, CB_ADDRESS, SCOREDMODEL_ID, APPLICANT_ID, LAST_ACTIVITY) values(theSource.cb_used, theSource.cb_address, theSource.scoredmodel_id, theSource.applicant_id, theSource.last_activity)';
    stmt2 varchar2(4000) := 'MERGE into edm_application theTarget USING (select * from '||from_schema||'.edm_application@'||remote_data_link||' where last_activity > :l_last_process_date) theSource ON (theTarget.edm_appl_id = theSource.edm_appl_id) WHEN MATCHED THEN UPDATE SET theTarget.APP_REF_KEY = theSource.APP_REF_KEY, theTarget.IMPORT_REF_KEY = theSource.IMPORT_REF_KEY, theTarget.LAST_ACTIVITY = theSource.LAST_ACTIVITY WHEN NOT MATCHED THEN INSERT (EDM_APPL_ID, APP_REF_KEY, IMPORT_REF_KEY, LAST_ACTIVITY) values(theSource.EDM_APPL_ID, theSource.APP_REF_KEY, theSource.IMPORT_REF_KEY, theSource.LAST_ACTIVITY)';
    v_error varchar2(4000);
    T_MERGE VARCHAR2(4000);
    stmt3 varchar2(4000);
    BEGIN
    select merge_sql
    INTO T_MERGE
    from transfertables
    where table_name= 'edm_application';
    remote_data_link:= 'UDE_DATATRANSFER_LINK';
    FROM_SCHEMA := 'UDE_OLTP';
    --DBMS_OUTPUT.PUT_LINE(SUBSTR(stmt2,1,200));
    STMT2 := T_MERGE;
    dbms_output.put_line(from_schema||' '||remote_data_link||' '||l_last_process_date);
    EXECUTE IMMEDIATE stmt2 using l_last_process_date;
    --execute immediate stmt3 ;
    dbms_output.put_line(from_schema||' '||remote_data_link||' '||l_last_process_date);
    dbms_output.put_line(substr(stmt2,1,200));
    commit;
    EXCEPTION
    WHEN OTHERS THEN
    V_ERROR := SQLCODE||' '||SQLERRM;
    v_ERROR := V_ERROR ||' '||SUBSTR(stmt2,1,200);
    DBMS_OUTPUT.PUT_LINE(V_ERROR);
    --dbms_output.put_line(substr(stmt2,1,200));
    END;
    I get ora-00900 invalid sql statement
    can somebody explain why this happens
    Thanks

    I agree with jan and anthony. Your post is too long and ill-formatted. However here's my understanding of your problem (with examples though slightly different ones).
    1- I have a function that returns number of records in a any given table.
      1  CREATE OR REPLACE FUNCTION get_count(p_table varchar2)
      2     RETURN NUMBER IS
      3     v_cnt number;
      4  BEGIN
      5    EXECUTE IMMEDIATE('SELECT count(*) FROM '||p_table) INTO v_cnt;
      6    RETURN v_cnt;
      7* END;
    SQL> /
    Function created.
    SQL> SELECT get_count('emp')
      2  FROM dual
      3  /
    GET_COUNT('EMP')
                  14
    2- I decide to move the statement to a database table and recreate my function.
    SQL> CREATE TABLE test
      2  (stmt varchar2(2000))
      3  /
    Table created.
    SQL> INSERT INTO test
      2  VALUES('SELECT count(*) FROM p_table');
    1 row created.
    SQL> CREATE OR REPLACE FUNCTION get_count(p_table varchar2)
      2     RETURN NUMBER IS
      3     v_cnt number;
      4     v_stmt varchar2(4000);
      5  BEGIN
      6     SELECT stmt INTO v_stmt
      7     FROM test;
      8     EXECUTE IMMEDIATE(v_stmt) INTO v_cnt;
      9     RETURN v_cnt;
    10  END;
    11  /
    Function created.
    SQL> SELECT get_count('emp')
      2  FROM dual
      3  /
    SELECT get_count('emp')
    ERROR at line 1:
    ORA-00942: table or view does not exist
    ORA-06512: at "SCOTT.GET_COUNT", line 8
    ORA-06512: at line 1
    --p_table in the column is a string and has nothing to do with p_table parameter in the function. And since there's no p_table table in my schema function returns error on execution. I suppose this is what you mean by "sql statement in a table not accepting variable"
    3- I rectify the problem by recreating the function.
      1  CREATE OR REPLACE FUNCTION get_count(p_table varchar2)
      2     RETURN NUMBER IS
      3     v_cnt number;
      4     v_stmt varchar2(4000);
      5  BEGIN
      6     SELECT replace(stmt,'p_table',p_table) INTO v_stmt
      7     FROM test;
      8     EXECUTE IMMEDIATE(v_stmt) INTO v_cnt;
      9     RETURN v_cnt;
    10* END;
    SQL> /
    Function created.
    SQL> SELECT get_count('emp')
      2  FROM dual
      3  /
    GET_COUNT('EMP')
                  14
    Hope this gives you some idea.-----------------------
    Anwar

  • Assigning values to 2 fields using sql statement

    db11g , apex 4.0 and firefox 24 ,
    hi all ,
    i am trying to follow this tutorial to assign values to 2 items on a page using sql statement ,
    and i am using the same sql statement the tutorial uses
    select d.loc location, count(e.empno) num_employees from dept d, emp e where d.deptno = e.deptno(+) and d.deptno = :P3_DEPTNO group by d.loc -- btw , what does the "+" sign mean?
    after the e.deptno in the where condition .
    but i am facing this error
    1 error has occurred
    Wrong number of columns selected in the SQL query. See Help of attribute for details.
    and it does not work with two columns in the select statement under any conditions , i tried to remove the group function and the group clause ,
    it does not work unless i use only one column in the select statement ??
    thanks

    Pars
    And how exactly is this rewrite of the sql statement resolving the OP's issue.
    You are still using more than 1 column which will still result in the error message:
    Wrong number of columns selected in the SQL query.
    As mentioned in my earlier post APEX 4.0 (the version the OP is using) does not handle a sql statement with multiple columns for the dynamic action Set Value.
    Which means the fastest  and simplest solution is splitting up the dynamic action in multiple Set Value actions.
    Using this plugin or upgrade to a newer apex version would also be a possibility.
    Nicolette

  • [0098]SQL*Plus encountered oracle error 100 while executing SQL Statement

    Hi,
    i'm trying to delete duplicate records from a table and running following script. this script is triggered from a unix script. it successfully deletes the records but in the last throws following error message,
    :[0098]SQL*Plus encountered oracle error 100 while executing SQL Statement:2:Investigation required:
    can anybody please help? below is the script.
    DECLARE
    --CURSOR FOR DUPLICATE ROWS
    CURSOR CUR_DUPLICATE_ROWS IS
    Select RMS_NOTE_ID, RMS_SUMMARY_NOTE_ID, count(*) cnt from PARTY_NOTE
    group by RMS_NOTE_ID,RMS_SUMMARY_NOTE_ID having count(*) > 1;
    var_date PARTY_NOTE.PARTY_NOTE_CREATED_DATE%TYPE;
    BEGIN
    FOR DUPLICATE_ROWS_REC IN CUR_DUPLICATE_ROWS
    LOOP
    delete from party_note
    where RMS_NOTE_ID= DUPLICATE_ROWS_REC.RMS_NOTE_ID
    and RMS_SUMMARY_NOTE_ID= DUPLICATE_ROWS_REC.RMS_SUMMARY_NOTE_ID
    and rowid not in (select max(rowid) from party_note
    where RMS_NOTE_ID= DUPLICATE_ROWS_REC.RMS_NOTE_ID and RMS_SUMMARY_NOTE_ID= DUPLICATE_ROWS_REC.RMS_SUMMARY_NOTE_ID);
    commit;
    END LOOP;
    EXCEPTION
    WHEN NO_DATA_FOUND THEN
    NULL;
    WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE(SQLERRM);
    ROLLBACK;
    END;

    Try this:
    delete party_note
    where  rowid not in (select max(rowid)
                         from   party_note
                         group  by rms_note_id, rms_summary_note_id
    commit;No need for cursors and loops.
    And when that's completed, consider ALTERing the table to add a unique index (or even a primary key) so you'll never need to do this again.

  • Pass ORG_ID as sql statement for parameter in request set

    We are in a multi-org environment. We are running the request PRC: Generate Draft Revenue for a Single Project as part of the request set. We want the request to automatically fill in the open pa period as the accrue through date. We have been using the SQL Statement below as the value for the accrue through date parameter.
    select end_date
    from pa_periods_all
    where status = 'O'
    and current_pa_period_flag = 'Y'
    Unfortunately that does not limit to a specific company. We a company that still have DEC-05 while another has an open period of JAN-06. This is causing the program fits. How do I pass the org_id to the request? [in beginners terms please]
    Thanks.
    Anne

    No idea what might be wroong without more info...
    Do some output. Test the ${params.id} variable passed to the second jsp. If that is correct, then error is in the select statement or display of jsp2. If it is correct the error comes from jsp1.
    If I have to guess, then I would say the error comes from JSP1, and the ${row.vac_id} should only be called once. In which case I would do something like this:
    //in jsp 1
                <c:forEach var="row" items="${results.rows}"  varStatus="counter"  >
                    <c:set var="vac_id" value="${row.vac_id}" scope="page"/>
                    <tr>
                        <td>${vac_id}</td>
                        <td><a href="vacancydetails.jsp?id=${vac_id}">More</a></td>But that is a guess only...
    Errr... Hold on to that as reference, but the it is entirely likely that I misspelled ${params.id} It may be ${param.id} I forget and away from my machine right now...

  • Pass parameter to sql statement in query manager

    Hai to all,
               I want to pass the percentage  as the parameter into the sql statemnet.i what to execute it in the query manager.
              If i execute that statement then cann't found the tablename error is coming.
             Other than the data in the table (general data)  pass to the parameter in the sql at runtime.
    for example:
    select [%0] *100
    how to pass 10 to that sql statement.
    Please help me...
    Regards,
    Raji.

    Hi Ramya,
    You can create a SP with parameters to accept and then execut this SP from SAP Business One Query Manager by passing the parameter (in your case 10). The result will be as desired.
    Ex:
    Create this Procedure in SQL Management Studio
    create proc Test(@a as int)
    as
    begin
    select (@a*100)
    end
    To Execute the Query use this Query and pass the desired values with parameters
    execute Test 10
    Regards,
    Reno

  • Using arrays in sql statement

    Hello,
    I would like to use integer array( say..int count[] = new int[3];) on my sql statement to retrieve some values. Is there a way to use int array variable in sql statement?. If yes, how should I approach doing that?.
    Thank You in Advance.
    Regards,
    Pinal.

    I'm going to be honest, I'm not so sure there is such a thing in standard SQL syntax so it would depend upon the database you were using as to whether this option was available as part of the SQL language.
    My suggestion would be to cheat, naughty I know:String arrayString = "";
    for (int i = 0; i < arrayInt.size(); i++) {
      arrayString += "**" + arrayInt;
    arrayString = arrayString.substring(2, arrayString.length());Then just parse arrayString in to an SQL VARCHAR or TEXT field.
    Obviously when you return it just use StringTokenizer to split the string up using your deliminator (in this case **) and then convert the values back into an int array.
    I'm not sure how efficient that code would be but it should do the job.

Maybe you are looking for