MViews with Aggregates -- SELECT COUNT(DISTINCT(x))

Hi all,
In the documentation of MViews with Aggregates says that only SUM, COUNT, AVG, STDDEV, VARIANCE, MIN and MAX are supported for fast refresh
If we consider <expr> = DISTINCT(x)
can I fast refresh my mviews containing a COUNT(<expr>) ???
Thanks in advanced
aLeX

Look here..
http://download-uk.oracle.com/docs/cd/B19306_01/server.102/b14200/functions032.htm#i82697
Bye
Acr

Similar Messages

  • Select count distinct

    Hi, Anybody can help !
    I have problem with select count distinct.
    example :
    select distinct custid from order_h
    total result : 141 rows selected.
    but :
    select count(distinct custid) from order_h
    result :
    COUNT(DISTINCTCUSTID)
    140
    Why the total difference, for listing 141 but for count 140 ?
    Is my statement wrong ? How to use count and distinct ?
    Thank's

    Look here..
    http://download-uk.oracle.com/docs/cd/B19306_01/server.102/b14200/functions032.htm#i82697
    Bye
    Acr

  • Logical Aggregate Column (count(distinct)) Does Not Group for SQL Server DB

    When utilizing the count(distinct column_name) aggregate function within a Logical Fact source in the Business Model and Mapping layer in the RPD file the output in BI Answers is not grouping correctly for SQL Server 2008 database sources only. All Oracle database sources represent the same aggregate column correctly within BI Answers.
    I am using OBIEE version 10.1.3.3.3
    Does anyone know how to resolve this issue?
    Thanks in advance,
    Kyle

    I thought that I would update my current findings with this issue. If you display the report in BI Answers as a Pivot Table view the aggregate column displays properly, it does not in a Table or Compound Layout view for some reason. I am still working with Oracle Support on this.

  • What's wrong with my SELECT/COUNT(*) statement?

    I am trying to get a total count of records related to a single master record within one table, and if I test this in the DW recordset wizard, I get the results I need. By testing it, I mean if I enter something other than the default -1, where there are results related to another 'master record', then I end up with the correct amount of rows, but when I test it in a browser, all I am getting is '0' for all records.
    This bit of code is setting the 'master record ID' to which others will relate to:
    <?php $_GET['trcount'] = $row_rs_replycount['fld_fID'] ?>
    This is my recordset which is inline with the code which is inside a repeat region:
    <?php
    $threadreplys_rs_replycount = "3";
    if (isset($_GET['trcount'])) {
      $threadreplys_rs_replycount = $_GET['trcount'];
    mysql_select_db($database_conn_mrs, $conn_mrs);
    $query_rs_replycount = sprintf("SELECT *, COUNT(*) AS countTOT FROM tbl_forumPOSTS WHERE fld_fTHREADID = %s ORDER BY fld_fID DESC", GetSQLValueString($threadreplys_rs_replycount, "int"));
    $rs_replycount = mysql_query($query_rs_replycount, $conn_mrs) or die(mysql_error());
    $row_rs_replycount = mysql_fetch_assoc($rs_replycount);
    $totalRows_rs_replycount = mysql_num_rows($rs_replycount);
    ?>                       
    And this is the code to display the total number of records that are related
    <?php echo $row_rs_replycount['countTOT']; ?>
    As I say, I have it working when testing different default values in the recordset wizard, but not live on a page.
    Thanks.

    >"SELECT *, COUNT(*) AS countTOT FROM tbl_forumPOSTS WHERE....
    That SQL is not valid - at least not by SQL standards. If your query contains an aggregate, then all columns that are not aggregated must be in a group by clause. It's possible that MySQL implicitly adds all non-aggreated columns to a group by, but you should probably fix it anyway. If you don't need to use the other columns from that table in the recordset, then just remove the * from the select list.
    "SELECT COUNT(*) AS countTOT FROM tbl_forumPOSTS WHERE....
    If you still have a problem, then output the value in $totalRows_rs_replycount to see if you are getting any rows returned from your query.
    Next, comment out these lines:
    if (isset($_GET['trcount'])) {
      $threadreplys_rs_replycount = $_GET['trcount'];
    to make sure any value in trcount is not interfering with the default value of '3' and see if that returns any results.

  • Select count distinct problem

    Hi,
    I have a tabe "M" that as messages, each message has a priority and is part of a departement. Now i wanted to create a report that count the number of messeges by departement group by priority and the total.............. something like this:
    Departement Priority1 Priority2 Priority3 Total
    A 1 2 3 6
    B 2 3 3 8
    C 1 1 1 3
    Can someboby help me please
    Than's
    Luis

    Unfortunately prior to 11g Oracle doesn't supply any means of creating cross tab queries, so any solution prior to 11g is going to rely on static views.
    However, if you don't mind having the data go down instead of accross you could use this:
    with m as (select 'high' priority, 'department A' department, 1 id_message from dual
      union all select 'medium', 'department A', 2 from dual
      union all select 'high',   'department B', 3 from dual
      union all select 'medium', 'department C', 4 from dual
      union all select 'high',   'department C', 5 from dual
      union all select 'medium', 'department B', 6 from dual
      union all select 'low',    'department A', 7 from dual
      union all select 'medium', 'department A', 8 from dual
      union all select 'low',    'department A', 9 from dual
      union all select 'high',   'department B', 10 from dual
      union all select 'low',    'department C', 11 from dual
      union all select 'medium', 'department C', 12 from dual
      union all select 'high',   'department B', 13 from dual
      union all select 'medium', 'department B', 14 from dual
      union all select 'medium', 'department B', 15 from dual
      union all select 'low',    'department B', 16 from dual
      union all select 'low',    'department C', 17 from dual
      union all select 'high',   'department C', 18 from dual
    select department, priority, count(id_message) from m
    group by rollup (department, priority)
    order by department, priority
    DEPARTMENT   PRIORITY COUNT(ID_MESSAGE)
    department A high     1
    department A low      2
    department A medium   2
    department A (null)   5
    department B high     3
    department B low      1
    department B medium   3
    department B (null)   7
    department C high     2
    department C low      2
    department C medium   2
    department C (null)   6
    (null)       (null)   18
    13 rows selectedor
    select department, priority, count(id_message) from m
    group by department, rollup (priority)
    order by department, priority
    DEPARTMENT   PRIORITY COUNT(ID_MESSAGE)
    department A high     1
    department A low      2
    department A medium   2
    department A (null)   5
    department B high     3
    department B low      1
    department B medium   3
    department B (null)   7
    department C high     2
    department C low      2
    department C medium   2
    department C (null)   6
    12 rows selected

  • Select count(x) on a table with many column numbers?

    Hi all,
    i have a table with physical data with 850 (!!) colums and
    ~1 Million rows.
    The select count(cycle)from test_table Statement is very, very slow
    WHY?
    The select count(cycle)from test_table is very fast by e.g 10 Colums. WHY?
    What has the number of columns, to do with the SELECT count(cyle).... statement?
    create test_table(
    cycle number primary key,
    stamp date,
    sensor 1 number,
    sensor 2 number,
    sensor_849 number,
    sensor_850 number);
    on W2K Oracle 9i Enterprise Edition Release 9.2.0.4.0 Production
    Can anybody help me?
    Many Thanks
    Achim

    hi lennert, hi all,
    many thanks for all the answers. I�m not an Oracle expert.
    Sorry for my english.
    Hi Lennert,
    you are right, what must i do to use the index in the
    query? Can you give me a pointer of direction, please?
    Many greetings
    Achim
    select count(*) from w4t.v_tfmc_3_blocktime;
    COUNT(*) ==> Table with 3 columns (very fast)
    306057
    Ausf�hrungsplan
    0 SELECT STATEMENT Optimizer=CHOOSE
    1 0 SORT (AGGREGATE)
    2 1 TABLE ACCESS (FULL) OF 'V_TFMC_3 _BLOCKTIME'    
    Statistiken
    0 recursive calls
    0 db block gets
    801 consistent gets
    794 physical reads
    0 redo size
    388 bytes sent via SQL*Net to client
    499 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    1 rows processed
    select count(*) from w4t.v_tfmc_3_value;
    COUNT(*)==> Table with 850 columns (very slow)
    64000
    Ausf�hrungsplan
    0 SELECT STATEMENT Optimizer=CHOOSE
    1 0 SORT (AGGREGATE)
    2 1 TABLE ACCESS (FULL) OF 'V_TFMC_3 _VALUE'    
    Statistiken
    1 recursive calls
    1 db block gets
    48410 consistent gets
    38791 physical reads
    13068 redo size
    387 bytes sent via SQL*Net to client
    499 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    1 rows processed

  • "group by" slow for using "count(distinct some_column)" - a better way?

    Hi all,
    i have an
    select
    count(distinct some_column),
    from [...]
    group by [...];
    Which is slowed down for the "*count(distinct some_column)*".
    The "group by" aggregates base records.
    But the base records have 1:n for some #1 event #n records each.
    Some of the #n records fall into group by result record (A), some other into group by result record (B).
    But each shall only count +1 per event - disregarding how many of the #n record have fallen into that category.
    Is there another (faster) way to count for this?
    - thanks!
    best regards,
    Frank
    Edited by: user8704911 on Jun 29, 2011 1:30 AM

    Hi Dom,
    incidentally i went in the direction you proposed:
    I replaced the pl/sql collection with the global temporary table.
    But the reason for doing this was a different one:
    I recognized, that the group by is much faster, if applied on table or global temporary table.
    However i first just moved the data from pl/sql collection to global temporary table in order to apply the group by there.
    Then the group by is much faster - but the moving of data from pl/sql collection to global temporary table then took away the time.
    So it was not the group by, but in general the read-access to the pl/sql collection (btw, around #65,000 records).
    Now having completely replaced the pl/sql collection with global temporary table everything is fine.
    cheers,
    Frank

  • Count Distinct over a Window

    Hi everyone,
    An analyst on my team heard of a new metric called a "Stickiness" metric. It basically measures how often users are coming to your website overtime.
    The definition is as follows:
    # Unique Users Today/#Unique users Over Last 7 days
    and also
    # Unique Users Today/#Unique users Over Last 30 days
    We have visit information stored in a table W_WEB_VISIT_F. For the sake of simplicity say it has columns VISIT_ID, VISIT_DATE and USER_ID (there are several more dimensional columns it has but I want to keep this exercise simple).
    I want to create an aggregate table called W_WEB_VISIT_A that pre-aggregates the three values I need per day: # Unique Users Today, #Unique users Over Last 7 days and #Unique users Over Last 30 days. The only way I can think of building the aggregate table is as follows
    WITH AGG AS (
    SELECT
    VISIT_DATE,
    USER_ID
    FROM W_WEB_VISIT_F
    GROUP BY
    VISIT_DATE,
    USER_ID
    select
    VISIT_DATE
    COUNT(DISTINCT USER_ID) UNIQUE_TODAY,
    (select count(distinct hist.USER_ID) from agg hist where hist.VISIT_DATE between src.VISIT_DATE - 6 and src.VISIT_DATE) SEVEN_DAYS,
    (select count(distinct hist.USER_ID) from agg hist where hist.VISIT_DATE between src.VISIT_DATE - 29 and src.VISIT_DATE) THIRTY_DAYS
    from agg
    group by visit_date
    The problem I am having is that W_WEB_VISIT_F has several million records in it and I can't get it the above query to complete. It ran over night and didn't complete.
    Is there a fancy 11g function I can use to do this for me? Is there a more efficient method?
    Thanks everyone for the help!
    -Joe
    Edited by: user9208525 on Jan 13, 2011 6:24 AM
    You guys are right. I missed the group by I had in the WITH Clause.

    Hi,
    Haven't used the windowing clause a lot, so I wanted to give a try.
    I made up some data with this query :create table t as select sysdate-dbms_random.value(0,10) visit_date, mod(level,5)+1 user_id
    from dual
    connect by level <= 20;Which gave me following rows :Scott@my10g SQL>select * from t order by visit_date;
    VISIT_DATE             USER_ID
    03/01/2011 13:17:10          1
    04/01/2011 05:30:30          4
    04/01/2011 08:08:13          5
    04/01/2011 14:42:24          3
    04/01/2011 20:20:58          3
    05/01/2011 17:29:24          2
    05/01/2011 17:40:20          4
    05/01/2011 18:32:56          2
    06/01/2011 04:12:53          5
    06/01/2011 08:59:18          2
    06/01/2011 09:04:26          3
    06/01/2011 10:14:20          1
    06/01/2011 14:22:54          1
    06/01/2011 19:39:04          1
    08/01/2011 14:44:18          5
    08/01/2011 21:38:04          5
    11/01/2011 04:56:05          4
    11/01/2011 18:52:29          2
    11/01/2011 23:57:30          4
    13/01/2011 07:24:22          3
    20 rows selected.I came up to that query :select
            v.*,
            case
                    when unq_l3d is null then -1
                    else trunc(unq_today/unq_l3d,2)
            end ratio
    from (
            select distinct trcdt, unq_today, unq_l3d
            from (
                    select
                    trcdt,
                    count(user_id)
                    over (
                            order by trcdt
                            range between numtodsinterval(1,'DAY') preceding and current row
                    ) unq_today,
                    count(user_id)
                    over (
                            order by trcdt
                            range between numtodsinterval(3,'DAY') preceding and current row
                    ) unq_l3d
                    from (
                            select distinct trunc(visit_date) trcdt, user_id from t
    ) v
    order by trcdtWith my sample data, it gives me :TRCDT                UNQ_TODAY    UNQ_L3D RATIO
    03/01/2011 00:00:00          1          1  1.00
    04/01/2011 00:00:00          4          4  1.00
    05/01/2011 00:00:00          5          6  0.83
    06/01/2011 00:00:00          6         10  0.60
    08/01/2011 00:00:00          1          7  0.14
    11/01/2011 00:00:00          2          3  0.66
    13/01/2011 00:00:00          1          3  0.33
    7 rows selected.where :
    - UNQ_TODAY is the number of distinct user_id in the day
    - UNQ_L3D is the number of distinct user_id in the last 3 days
    - RATIO is UNQ_TODAY divided by UNQ_L3D +(when UNQ_L3D is not zero)+
    It seems quite correct, but you would have to modify the query to fit to your needs and double-check the results !
    Just noticed that my query is all wrong*... must have been missing coffeine, or sleep.... but I'm still trying !
    Edited by: Nicosa on Jan 13, 2011 5:29 PM

  • Sub-Select Count query breaking TOAD

    Oracle 10.2.0.4.0
    Running TOAD 9.1
    I am running some SQL on our eBusiness Suite:
    SELECT pha.segment1
         , pha.type_lookup_code
         , (SELECT COUNT(DISTINCT pha2.po_header_id)
              FROM po.po_headers_all pha2
                 , po.po_lines_all pla
             WHERE pha2.po_header_id = pla.po_header_id
               AND pla.contract_id = pha.po_header_id) po_count
         , (SELECT MAX(pha2.creation_date)
              FROM po.po_headers_all pha2
                 , po.po_lines_all pla
             WHERE pha2.po_header_id = pla.po_header_id
               AND pla.contract_id = pha.po_header_id) latest_cpa_po
      FROM po.po_headers_all pha
         , po.po_vendors pv
         , po.po_vendor_sites_all pvsa
    WHERE pha.vendor_id = pv.vendor_id
       AND pha.vendor_site_id = pvsa.vendor_site_id
    --   AND pv.VENDOR_NAME LIKE 'H%'
       AND pha.vendor_id = 98
       AND pha.type_lookup_code = 'CONTRACT'
       AND pha.org_id IN(7041, 7042);The above query runs quicky (approx. 1 second). If I take out the AND pha.vendor_id = 98 then the query takes a few minutes to run.
    When I try to export it, or scroll down to view > 500 rows, TOAD crashes.
    I know this isn't a TOAD forum, but I think that this is probably an issue with my no doubt rubbish SQL.
    If I take out this sub-select, then the problem doesn't happen:
         , (SELECT COUNT(DISTINCT pha2.po_header_id)
              FROM po.po_headers_all pha2
                 , po.po_lines_all pla
             WHERE pha2.po_header_id = pla.po_header_id
               AND pla.contract_id = pha.po_header_id) po_countHowever, I can't work out a better way of getting the data I need.
    The sub-select counts POs which have been raised where the contractID on the PO line is the same as the PO Header ID from the main query.
    Any advice please, on what I could do to sort this out would be much appreciated.
    Thanks!

    Hi,
    It looks like you can replace both scalar sub-queries with a join, like this:
    WITH     header_lines_summary     AS
         SELECT    pla.contract_id
              ,       COUNT (DISTINCT pha2.po_header_id)     AS po_count
              ,       MAX (pha2.creation_date)          AS latest_cpa_po
              FROM        po.po_headers_all pha2
                 ,        po.po_lines_all   pla
             WHERE        pha2.po_header_id = pla.po_header_id
          GROUP BY       pla.contract_id
    )                                        -- Everything up to this line is new
    SELECT pha.segment1
         , pha.type_lookup_code
         , hls.po_count                              -- Changed
         , hls.latest_cpa_po                         -- Changed
      FROM po.po_headers_all     pha
         , po.po_vendors           pv
         , po.po_vendor_sites_all      pvsa
         , header_lines_summary     hls                    -- New
    WHERE pha.vendor_id          = pv.vendor_id
       AND pha.vendor_site_id     = pvsa.vendor_site_id
       AND pha.po_header_id          = hls.contract_id (+)          -- New
    --   AND pv.VENDOR_NAME      LIKE 'H%'
       AND pha.vendor_id           = 98
       AND pha.type_lookup_code      = 'CONTRACT'
       AND pha.org_id           IN (7041, 7042);Aside from the sub-query (which is entirely new), the query above is just what you posted, with 2 lines changed and 2 lines added, as marked.
    This should be more efficient, but I don't know for certain that it will solve the Toad problem.
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables, and also post the results you want from that data.
    It never hurts to say what version of Oracle you're using.

  • Help with doing SELECT sub query within the SET of an UPDATE statement

    After doing some research, it appears as if it's possible to use a SELECT subquery in the SET of an UPDATE statement.  i did find some examples and here is my code, however when I click the "check" button it's saying the field (my entire select subquery) is unknown and neither in one of the specified tables or defined by a "DATA".  Do I have a syntax issue or is there another reason why it's not taking this as a valid statement?  Thanks for the help!
    LOOP AT IT_DATA
    UPDATE /BIC/AZDP_O0140
       SET /BIC/ZCOUNTER = (SELECT COUNT( DISTINCT MATERIAL )
                            FROM /BIC/AZDP_O0140
                            WHERE MATERIAL EQ IT_DATA-MATERIAL
                            GROUP BY MATERIAL).
    ENDLOOP.

    my Update does indeed have a WHERE clause but because of the issue i'm having, all my criteria in my WHERE is black text in the ABAP editor.  The editor doesn't even recognize the keywords "WHERE" or "EQ".  Below is my entire statement which contains all WHERE criteria in both the Update and the Subquery, i've just removed it for testing to help simplify the query and eliminate as many other factors as posisble that may be causing problems:
    LOOP AT IT_DATA.
       UPDATE /BIC/AZDP_O0140
       SET /BIC/ZCOUNTER = (SELECT COUNT( DISTINCT MATERIAL ) FROM /BIC/AZDP_O0140
       WHERE WHSE_NUM EQ IT_DATA-WAREHOUSE
        AND  PLANT EQ IT_DATA-PLANT
        AND  /BIC/ZTRAN_NO EQ IT_DATA-TRANS_NUM
        AND  DELIV_NUMB EQ IT_DATA-DELIVERY
        AND  MATERIAL EQ IT_DATA-MATERIAL
        GROUP BY MATERIAL)
       WHERE WHSE_NUM EQ IT_DATA-WAREHOUSE
        AND  PLANT EQ IT_DATA-PLANT
        AND  /BIC/ZTRAN_NO EQ IT_DATA-TRANS_NUM
        AND  DELIV_NUMB EQ IT_DATA-DELIVERY
        AND  MATERIAL EQ IT_DATA-MATERIAL.
    ENDLOOP.
    i should also mention the sources i found were not within the SAP Library but instead on other third-party ABAP websites.  so because i was having issues i wanted to post here to see if anyone else has come up with a working solution.  but if this cannot be done i can likely come up with a solution for my needs using multiple internal tables, this would just have been much easier since i can get a query like this to do what i want in SQL Server.  Thought i could utilize this in ABAP as well.

  • Efficiency of "Count(Distinct Case" in SQL

    Hi,
    Could you please let me know if "Count(Distinct Case" statement is efficient for a million rows or is there a better way to do it
    For example -this table below contains a set of customers with status flag as 'new' or 'existing'.
    CREATE TABLE tableA
    ( cust_id NUMBER
    , status VARCHAR(10)
    ,txn_id NUMBER
    INSERT INTO tableA (cust_id, status,txn_id) VALUES ( 6433, 'New', 11);
    INSERT INTO tableA (cust_id, status,txn_id) VALUES ( 6433, 'New', 21);
    INSERT INTO tableA (cust_id, status,txn_id) VALUES ( 1234, 'existing', 31);
    INSERT INTO tableA (cust_id, status,txn_id) VALUES ( 1234, 'existing', 41);
    INSERT INTO tableA (cust_id, status,txn_id) VALUES ( 7654, 'New', 51);
    INSERT INTO tableA (cust_id, status,txn_id) VALUES ( 7654, 'New', 61);
    INSERT INTO tableA (cust_id, status,txn_id) VALUES ( 9999, 'existing', 71);
    INSERT INTO tableA (cust_id, status,txn_id) VALUES ( 8888, 'New', 81);
    INSERT INTO tableA (cust_id, status,txn_id) VALUES ( 8888, 'existing', 91);
    INSERT INTO tableA (cust_id, status,txn_id) VALUES ( 2121, 'New', 100);
    am using the below SQL to calculate the number of distinct customers with status 'New'.
    Select
    Count(Distinct Case When status = 'New' Then cust_id end) New_Cust_Cnt
    from tableA
    Regards
    -Learnsequel

    san wrote:
    Hello,
    Select
    Count(Distinct Case When status = 'New' Then cust_id end) New_Cust_Cnt
    from tableA
    _Use like this:_
    Select
    Count(cust_id) New_Cust_Cnt
    from tableA
    where status='new';And also you can create index on status you will get faster.
    Thanks,
    SanjeevaAny how you have to use DISTINCT keywork. Otherwise you will not get the correct results for the OP's data.

  • COUNT(DISTINCT) on multiple columns?

    Is there an easier way of doing a COUNT(DISTINCT...) on multiple items than converting them to strings and concatenating them?
    i.e. if I have a table with column string1 as VARCHAR2(1000), number2 as NUMBER, and date3 as DATE, and I want a count on how many distinct combinations of the three exist, is there a better way than:
    SELECT COUNT(DISTINCT string1 || TO_CHAR(number2) || TO_CHAR(date3, 'YYYYMMDD'))-- Don

    Hi,
    Why not a group by?
    SQL> ed
    Wrote file afiedt.buf
      1  with t as
      2  (
      3  select 'string1' string1, 1 number1, to_date('10-NOV-2009','DD-MON-YYYY') date1 from dual
      4  union all select 'string2',1,to_date('10-NOV-2009','DD-MON-YYYY') from dual
      5  union all select 'string1',1,to_date('11-NOV-2009','DD-MON-YYYY') from dual
      6  union all select 'string1',2,to_date('11-NOV-2009','DD-MON-YYYY') from dual
      7  union all select 'string2',1,to_date('10-NOV-2009','DD-MON-YYYY') from dual
      8  )
      9  select string1, number1, date1 from t
    10* group by string1, number1, date1
    SQL> /
    STRING1    NUMBER1 DATE1
    string1          1 11-NOV-09
    string2          1 10-NOV-09
    string1          1 10-NOV-09
    string1          2 11-NOV-09
    SQL> ed
    Wrote file afiedt.buf
      1  with t as
      2  (
      3  select 'string1' string1, 1 number1, to_date('10-NOV-2009','DD-MON-YYYY') date1 from dual
      4  union all select 'string2',1,to_date('10-NOV-2009','DD-MON-YYYY') from dual
      5  union all select 'string1',1,to_date('11-NOV-2009','DD-MON-YYYY') from dual
      6  union all select 'string1',2,to_date('11-NOV-2009','DD-MON-YYYY') from dual
      7  union all select 'string2',1,to_date('10-NOV-2009','DD-MON-YYYY') from dual
      8  )
      9  select string1, number1, date1 from t
    10  group by string1, number1, date1
    11* having count(*) > 1
    SQL> /
    STRING1    NUMBER1 DATE1
    string2          1 10-NOV-09-Arun

  • Performance issue when using select count on large tables

    Hello Experts,
    I have a requirement where i need to get count of data  from a database table.Later on i need to display the count in ALV format.
    As per my requirement, I have to use this select count inside a nested loops.
    Below is the count snippet:
    LOOP at systems assigning <fs_sc_systems>.
    LOOP at date assigning <fs_sc_date>.
    SELECT COUNT( DISTINCT crmd_orderadm_i~header )
       FROM crmd_orderadm_i
       INNER JOIN bbp_pdigp
           ON crmd_orderadm_iclient EQ bbp_pdigpclient               "MANDT is referred as client
         AND crmd_orderadm_iguid  EQ bbp_pdigpguid
         INTO w_sc_count
    WHERE crmd_orderadm_i~created_at BETWEEN <fs_sc_date>-start_timestamp
         AND <fs_sc_date>-end_timestamp
         AND bbp_pdigp~zz_scsys   EQ <fs_sc_systems>-sys_name.
    endloop.
    endloop.
    In the above code snippet,
    <fs_sc_systems>-sys_name is having the system name,
    <fs_sc_date>-start_timestamp is having the start date of month
    and <fs_sc_date>-end_timestamp is the end date of month.
    Also the data in tables crmd_orderadm_i and bbp_pdigp is very large and it increases every day.
    Now,the above select query is taking a lot of time to give the count due to which i am facing performance issues.
    Can any one pls help me out to optimize this code.
    Thanks,
    Suman

    Hi Choudhary Suman ,
    Try this:
    SELECT crmd_orderadm_i~header
      INTO it_header                 " interna table
      FROM crmd_orderadm_i
    INNER JOIN bbp_pdigp
        ON crmd_orderadm_iclient EQ bbp_pdigpclient
       AND crmd_orderadm_iguid   EQ bbp_pdigpguid
       FOR ALL ENTRIES IN date
    WHERE crmd_orderadm_i~created_at BETWEEN date-start_timestamp
                                          AND date-end_timestamp
       AND bbp_pdigp~zz_scsys EQ date-sys_name.
        SORT it_header BY header.
        DELETE ADJACENT DUPLICATES FROM it_header
        COMPARING header.
        describe table it_header lines v_lines.
    Hope this information is help to you.
    Regards,
    José

  • 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

  • Counting distinct values???

    Hi all,
    Why does this not work?
    "Select count(distinct employee_id) from employee_table"
    I am looking to return the count of the distinct employee_id.

    because its not valid SQL
    try:
    select * from employee_table where employee_id in (select distinct employee_id from employee_table)not very neat but should work (on oracle or SQLserveR)

Maybe you are looking for