Count(*) with nested query

Hi,
I have a question about the count(*) with nested query.
I have a table T1 with these columns:
C1 number
C2 number
C3 number
C4 number
C5 number
(The type of each column is not relevant for the example.)
This query:
select C1, C2, C3, C4
from T1
group by C1, C2
it's not correct becausa C3 and C4 are not columns specified in the GROUP BY expression.
If if run this query:
select count(*)
from (select C1, C2, C3, C4
from T1
group by C1, C2)
I haven't an error message (the result is correctly the number of records).
Why?
Thanks.
Best regards,
Luca

Because you are just selecting count(*) and none of the columns from the subquery, Oracle is optimising it by ignoring the selected columns and just running the sub query with the group by columns. I know it seems odd, but if you take a basic example:
SQL> ed
Wrote file afiedt.buf
  1  select count(*)
  2  from (select empno, sal, mgr, deptno
  3  from emp
  4* group by deptno)
SQL> /
  COUNT(*)
         3... all columns but deptno are ignored
... but if you include one of the other columns, even if you group by that column...
SQL> ed
Wrote file afiedt.buf
  1  select count(*), empno
  2  from (select empno, sal, mgr, deptno
  3  from emp
  4  group by deptno)
  5* group by empno
SQL> /
group by empno
ERROR at line 5:
ORA-00979: not a GROUP BY expression
SQL>... the error returns, because you're forcing oracle to include the column in the subquery.

Similar Messages

  • Getting Counts with single query

    HI,
    I need help in writing a query that gets account counts in a single query,
    CREATE TABLE ACCOUNTINFO(     
    ACCOUNTID VARCHAR2(20 BYTE) NOT NULL,
    ACCOUNTNO VARCHAR2(10 BYTE) NOT NULL,
    LAST_DEPOSIT_DATE DATE,
    BALANCE NUMBER(10,0));
    I have a table like above and I am trying to write a query that gets
    Count of accounts with deposits made in last 1 month,
    Count of accounts with deposits made in last 2 months
    Account Count with balance > 0,
    Also, I need to join this ACCOUNTINFO with ACCOUNTMAIN to get name etc details
    CREATE TABLE ACCOUNTINFO(     
    EMPID VARCHAR2(20 BYTE) NOT NULL,
    FNAME VARCHAR2(30 BYTE) NOT NULL,
    MNAME VARCHAR2(30 BYTE),
    LNAME VARCHAR2(30 BYTE) NOT NULL,
    DOB DATE,
    ACCOUNTID VARCHAR2(20 BYTE));
    Question, how to write a query since I getting too-many counts (I have only 3 in sample above, actual goes on like 3-6, 6-9 etc).

    SELECT SUM  (CASE WHEN LAST_DEPOSIT>=ADD_MONTHS(SYSDATE,-1) THEN
                   1
                 ELSE
                   0
                 END
                ) COUNT_LAST_MONTH,
           SUM  (CASE WHEN LAST_DEPOSIT>=ADD_MONTHS(SYSDATE,-2) THEN
                   1
                 ELSE
                   0
                 END
                ) COUNT_LAST_TWO_MONTHS,
           SUM  (CASE WHEN BALANCE>0 THEN
                   1
                 ELSE
                   0
                 END
                ) COUNT_BALANCE_GREATER_ZERO
      FROM ACCOUNTINFO

  • Cursor with nested query in stored procedure problem

    Hello
    I'm trying to declare the folowing (example) cursor in a stored procedure in Oracle 8i:
    CURSOR RECORDS IS SELECT d.DUMMY, (SELECT dd.DUMMY FROM dual dd) FROM dual d;
    The nested part "(SELECT d.DUMMY FROM dual)" is not alowed, while the same query runs outside the stored procedure. Can someone explain why this is not alowed and how to solve the problem whitout rewriting the query?
    Tom

    When i run the same code in SQL plus:
    SQL> declare
    2 CURSOR RECORDS IS SELECT d.DUMMY, (SELECT dd.DUMMY FROM dual dd) FROM dual d;
    3 begin
    4 null;
    5 end;
    6 /
    CURSOR RECORDS IS SELECT d.DUMMY, (SELECT dd.DUMMY FROM dual dd) FROM dual d;
    FOUT in regel 2:
    .ORA-06550: line 2, column 36:
    PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:
    ( - + mod not null others <an identifier>
    <a double-quoted delimited-identifier> <a bind variable> avg
    count current exists max min prior sql stddev sum variance
    execute forall time timestamp interval date
    <a string literal with character set specification>
    <a number> <a single-quoted SQL string>
    ORA-06550: line 2, column 66:
    PLS-00103: Encountered the symbol "FROM" when expecting one of the following:
    ; return returning and or
    Different versions of Oracle?

  • How can I get record count with a query?

    In Client/Server pplication,the client send a query to server.
    How can server get record count by oracle call interface?
    Is it need execute "select count(*) from ...."?

    Yes.
    Either that or increment a counter for each record fetched and
    loop round until you hit the last record.
    The first method would be more efficient on large datasets.

  • Help with nested query

    Hi
    I'm trying to pull session details from our production server to a separate table. I need to gather in one query
    total count of sessions != to SYSTEM
    total count of inactive session != to SYSTEM
    average of last_call_et
    My table has 4 fields in it
    DATERUN     Timestamp(6)     11     -      6     -      nullable     -      -
         CON_TOT     Number     -      -      -      -      nullable     -      -
         INACTIVE_TOT     Number     -      -      -      -      nullable     -      -
    Avg_LastCall number
    For some reason I can't make this work. Any help would be appreciated.

    Hi
    I've abandoned my previous attempt and now trying the below. I am simply trying to capture the following info from the v$session table and transfer it into a table I have created.
    The source table is DB1.v$session
    The target table is DB2.sessions ( I have a working db link between the two)
    Desired data to be pulled from the v$session table:
    Count of total connections. (select count(*) from v$session where osuser !='SYSTEM';)
    Count of total inactive sessions (select count(*) from v$session where STATUS='INACTIVE' AND osuser !='SYSTEM';
    Average of v$session.last_call_et (select avg(last_call_et) from v$session where osuser !='SYSTEM';)
    My latest attempt using cursors:
    create or replace procedure Session_Count_SDEMR is
    BEGIN
    v_Total NUMBER;
    v_Inactive NUMBER;
    v_Avg_LC NUMBER;
    /* First cursor */
    cursor get_count is
    select count(*)
    from v$session@EMRLIVE
    where osuser != 'SYSTEM';
    /* Second cursor */
    cursor get_inactive is
    select count(*)
    from v$session@EMRLIVE
    where osuser != 'SYSTEM';
         /* Third cursor */
    cursor get_avget is
    select AVG(last_call_et)
    from v$session@EMRLIVE
    where osuser != 'SYSTEM';
    begin
    -- Open first cursor
    open get_count;
    loop
    fetch get_count into v_Total;
    open get_inactive;
    loop
    fetch get_inactive into v_Inactive;
                   open get_avget;
                   loop
    fetch get_avget into v_Avg_LC;
    end loop;
    close get_count;
    end loop;
    close get_inactive;
         end loop;
         close get_avget;
    Insert into sessions
         VALUES(SYSDATE, v_total, v_Inactive, v_Avg_LC);
    END;
    The error i get is:
    ERROR at line 51: PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:

  • Programmatically determine step count with nested sequences

    I have a program that uses the count of steps in a sequence to determine progress. I currently use a sequence pointer to call GetNumSteps for each group. What would be the best way to expand this to handle subsequences? In other words, if I have a top level sequence with 5 main steps, 0 setup and 0 cleanup but one of the steps is a sequence call and that sequence has 10 main steps, 0 setup and 0 cleanup steps, I want the count to be 15 and not 5. Thanks.
    -G-
    -G-

    Steve is correct, you would have to set this up using recursion where you count steps and also go into sequence calls to count their steps as well. There is no native way to do this in TestStand, you would have to program this with your language of choice and call that recursive function.
    Brandon Vasquez
    Applications Engineer
    National Instruments
    Brandon Vasquez | Software Engineer | Integration Services | National Instruments

  • Nested query in BPEL JDeveloper

    Hi,
    Can anyone help me with nested query writing in BPEL (JDeveloper)
    the query is :
    SELECT LENGTH, WIDTH, HEIGHT, WEIGHT,
    LENGTH*WIDTH* HEIGHT AS ITEM_CUBE
    FROM ITEM_SUPP_COUNTRY_DIM
    WHERE ITEM= &lt;Level1 item&gt;
    AND DIM_OBJECT= (SELECT CASE_NAME FROM ITEM_SUPPLIER WHERE ITEM=&lt;Item&gt; AND PRIMARY_SUPP_IND = &lsquo;Y')
    Please help me with the steps.
    Many thanks

    Hi,
    For the following query:
    SELECT S.STORE, S.STORE_NAME, A.ADD_1, A.ADD_2, A.ADD_3, A.CITY,A.STATE, A.POST, A.COUNTRY_ID, A.CONTACT_PHONE, A.CONTACT_NAME,S.STORE_OPEN_DATE, S.STORE_CLOSE_DATE, S.REMODEL_DATE, S.TRANSFER_ZONE,S.DISTRICT,S.STORE_TYPE
    FROM STORE S, ADDR A
    WHERE S.STORE= #store
    AND to_char(S.STORE) = #keyValue1
    AND A.MODULE = #module
    AND A.ADDR_TYPE = #type
    AND A.PRIMARY_ADDR_IND=#addrType
    the DB adapter shows this xml:
    &lt;?xml version = '1.0' encoding = 'UTF-8'?&gt;
    &lt;xs:schema targetNamespace="http://xmlns.oracle.com/pcbpel/adapter/db/WMSStoreDataLookUp" xmlns="http://xmlns.oracle.com/pcbpel/adapter/db/WMSStoreDataLookUp" elementFormDefault="qualified" attributeFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt;
    &lt;xs:element name="WMSStoreDataLookUpInput" type="WMSStoreDataLookUpInput"/&gt;
    &lt;xs:complexType name="WMSStoreDataLookUpInput"&gt;
    &lt;xs:sequence&gt;
    &lt;xs:element name="store" type="/&gt;<br /><br /> &lt;xs:element name="keyValue1" type="/&gt;
    &lt;xs:element name="module" type="/&gt;<br /><br /> &lt;xs:element name="type" type="/&gt;
    &lt;xs:element name="addrType" type="/&gt;<br /><br /> &lt;/xs:sequence&gt;<br /><br />&lt;/xs:complexType&gt;<br /><br />&lt;xs:element name="WMSStoreDataLookUpOutputCollection" type="WMSStoreDataLookUpOutputCollection" nillable="true"/&gt;<br /><br />&lt;xs:complexType name="WMSStoreDataLookUpOutputCollection"&gt;<br /><br />&lt;xs:sequence&gt;<br /><br />&lt;xs:element name="WMSStoreDataLookUpOutput" type="WMSStoreDataLookUpOutput" minOccurs="0" maxOccurs="unbounded"/&gt;<br /><br />&lt;/xs:sequence&gt;<br /><br />&lt;/xs:complexType&gt;<br /><br />&lt;xs:complexType name="WMSStoreDataLookUpOutput"&gt;<br /><br />&lt;xs:sequence&gt;<br /><br />&lt;xs:element name="S_STORE" type="xs:decimal" nillable="true"/&gt;<br /><br />&lt;xs:element name="S_STORE_NAME" type="xs:string" nillable="true"/&gt;<br /><br />&lt;xs:element name="A_ADD_1" type="xs:string" nillable="true"/&gt;<br /><br />&lt;xs:element name="A_ADD_2" type="xs:string" nillable="true"/&gt;<br /><br />&lt;xs:element name="A_ADD_3" type="xs:string" nillable="true"/&gt;<br /><br />&lt;xs:element name="A_CITY" type="xs:string" nillable="true"/&gt;<br /><br />&lt;xs:element name="A_STATE" type="xs:string" nillable="true"/&gt;<br /><br />&lt;xs:element name="A_POST" type="xs:string" nillable="true"/&gt;<br /><br />&lt;xs:element name="A_COUNTRY_ID" type="xs:string" nillable="true"/&gt;<br /><br />&lt;xs:element name="A_CONTACT_PHONE" type="xs:string" nillable="true"/&gt;<br /><br />&lt;xs:element name="A_CONTACT_NAME" type="xs:string" nillable="true"/&gt;<br /><br />&lt;xs:element name="S_STORE_OPEN_DATE" type="xs:dateTime" nillable="true"/&gt;<br /><br />&lt;xs:element name="S_STORE_CLOSE_DATE" type="xs:dateTime" nillable="true"/&gt;<br /><br />&lt;xs:element name="S_REMODEL_DATE" type="xs:dateTime" nillable="true"/&gt;<br /><br />&lt;xs:element name="S_TRANSFER_ZONE" type="xs:decimal" nillable="true"/&gt;<br /><br />&lt;xs:element name="S_DISTRICT" type="xs:decimal" nillable="true"/&gt;<br /><br />&lt;xs:element name="S" type="xs:string" nillable="true"/&gt;<br /><br />&lt;xs:element name="A_PRIMARY_ADDR_IND__addrType" type="xs:string" nillable="true"/&gt;<br /><br />&lt;/xs:sequence&gt;<br /><br />&lt;/xs:complexType&gt;<br /><br />&lt;/xs:schema&gt;<br /><br /><br /><br />Please, look at the last few lines of XML and let me know if this is correct..

  • How can I evaluate the count of a query I'd like to execute with a map...

    Hi. I have a problem with a query...
    I hava created a query which a execute with a Map (I use the
    executeWithMap(Map) method). The problem is that sometimes this query
    returns a large resultset. So, I would like to execute an other query
    (called query_count) before executing ther final query with the Map. If
    the query_count returns a count < 200, I execute the final query. How can
    I do ? There is an example I have read this in the documentation :
    Query query = pm.newQuery (Magazine.class, "price < 5");
    query.setResult ("count(this)");
    Long count = (Long) query.execute ();
    The problem in this example is that the query is not execute with a Map.
    So my question is : "How can we do the evalute the count of a query we
    would like to execute with a map ?". Thank you for any response.

    Hi John,
    You should be able to executeWithMap that query, too. Is that giving you
    problems?
    Note that there may be an easier solution. What do you do if there are more
    than 200 results? If, e.g., you just get the first N, then one option is to
    set the FetchBatchSize on the query to N (thus activating large result set
    support), and then call size () on the resulting Collection. This will
    issue a SELECT COUNT(*) to the database to determine the size automatically.
    Thanks,
    Greg
    "John" <[email protected]> wrote in message
    news:ctq9a8$4gr$[email protected]..
    >
    Hi. I have a problem with a query...
    I hava created a query which a execute with a Map (I use the
    executeWithMap(Map) method). The problem is that sometimes this query
    returns a large resultset. So, I would like to execute an other query
    (called query_count) before executing ther final query with the Map. If
    the query_count returns a count < 200, I execute the final query. How can
    I do ? There is an example I have read this in the documentation :
    Query query = pm.newQuery (Magazine.class, "price < 5");
    query.setResult ("count(this)");
    Long count = (Long) query.execute ();
    The problem in this example is that the query is not execute with a Map.
    So my question is : "How can we do the evalute the count of a query we
    would like to execute with a map ?". Thank you for any response.

  • Query rewrites with Nested materialized views with different aggregations

    Platform used : Oracle 11g.
    Here is a simple fact table (with measures m1,m2) and dimensions (a) Location (b) Calendar and (c) Product. The business problem is that aggregation operator for measure m1,m2 are different along location dimension and Calendar dimension. The intention is to preaggregate the measures for a product along the calendar dimension and Location dimension and store it as materialized views.
    The direct option is to define a materialized view with Inline queries (Because of the different aggrergation operator, it is not possible to write a query without Inline query). http://download-uk.oracle.com/docs/cd/B28359_01/server.111/b28313/qradv.htm#BABEAJBF documents the limitations that it works only for 'Text match' and 'Equivalent queries' and that is too limiting.
    So decided to have nested materialized view, with first view having just joins(my_dim_mvw_joins), the second view having aggregations along Calendar dimension (my_dim_mvw_calendar) and third view having aggregations along the Location dimension(my_dim_mvw_location). Obviously I do not want the query I fire to know about materialized views and I fire it against the fact table. I see that for the fired query (Which needs aggregations along both Calendar and Location), is rewritten with just second materialized view but not the third. (Had set QUERY_REWRITE_INTEGRITY as TRUSTED) .
    Wanted to know whether there are limitations on Query Writes with nested materialized views? Thanks
    (Have given a simple testable example below. Pls ignore the values given in 'CALENDAR_IDs', 'PRODUCT_IDs' etc as they are the same for all the queries)
    -- Calendar hierarchy table
    CREATE TABLE CALENDAR_HIERARCHY_TREE
    (     "CALENDAR_ID" NUMBER(5,0) NOT NULL ENABLE,
    "HIERARCHY1_ID" NUMBER(5,0),
    "HIERARCHY2_ID" NUMBER(5,0),
    "HIERARCHY3_ID" NUMBER(5,0),
    "HIERARCHY4_ID" NUMBER(5,0),
    CONSTRAINT "CALENDAR_HIERARCHY_TREE_PK" PRIMARY KEY ("CALENDAR_ID")
    -- Location hierarchy table
    CREATE TABLE LOCATION_HIERARCHY_TREE
    (     "LOCATION_ID" NUMBER(3,0) NOT NULL ENABLE,
    "HIERARCHY1_ID" NUMBER(3,0),
    "HIERARCHY2_ID" NUMBER(3,0),
    "HIERARCHY3_ID" NUMBER(3,0),
    "HIERARCHY4_ID" NUMBER(3,0),
    CONSTRAINT "LOCATION_HIERARCHY_TREE_PK" PRIMARY KEY ("LOCATION_ID")
    -- Product hierarchy table
    CREATE TABLE PRODUCT_HIERARCHY_TREE
    (     "PRODUCT_ID" NUMBER(3,0) NOT NULL ENABLE,
         "HIERARCHY1_ID" NUMBER(3,0),
         "HIERARCHY2_ID" NUMBER(3,0),
         "HIERARCHY3_ID" NUMBER(3,0),
         "HIERARCHY4_ID" NUMBER(3,0),
         "HIERARCHY5_ID" NUMBER(3,0),
         "HIERARCHY6_ID" NUMBER(3,0),
         CONSTRAINT "PRODUCT_HIERARCHY_TREE_PK" PRIMARY KEY ("PRODUCT_ID")
    -- Fact table
    CREATE TABLE RETAILER_SALES_TBL
    (     "PRODUCT_ID" NUMBER,
    "PRODUCT_KEY" VARCHAR2(50 BYTE),
    "PLAN_ID" NUMBER,
    "PLAN_PERIOD_ID" NUMBER,
    "PERIOD_ID" NUMBER(5,0),
    "M1" NUMBER,
    "M2" NUMBER,
    "M3" NUMBER,
    "M4" NUMBER,
    "M5" NUMBER,
    "M6" NUMBER,
    "M7" NUMBER,
    "M8" NUMBER,
    "LOCATION_ID" NUMBER(3,0),
    "M9" NUMBER,
    CONSTRAINT "RETAILER_SALES_TBL_LOCATI_FK1" FOREIGN KEY ("LOCATION_ID")
    REFERENCES LOCATION_HIERARCHY_TREE ("LOCATION_ID") ENABLE,
    CONSTRAINT "RETAILER_SALES_TBL_PRODUC_FK1" FOREIGN KEY ("PRODUCT_ID")
    REFERENCES PRODUCT_HIERARCHY_TREE ("PRODUCT_ID") ENABLE,
    CONSTRAINT "RETAILER_SALES_TBL_CALEND_FK1" FOREIGN KEY ("PERIOD_ID")
    REFERENCES CALENDAR_HIERARCHY_TREE ("CALENDAR_ID") ENABLE
    -- Location dimension definition to promote query rewrite
    create DIMENSION LOCATION_DIM
    LEVEL CHAIN IS LOCATION_HIERARCHY_TREE.HIERARCHY1_ID
    LEVEL CONSUMER_SEGMENT IS LOCATION_HIERARCHY_TREE.HIERARCHY3_ID
    LEVEL STORE IS LOCATION_HIERARCHY_TREE.LOCATION_ID
    LEVEL TRADING_AREA IS LOCATION_HIERARCHY_TREE.HIERARCHY2_ID
    HIERARCHY PROD_ROLLUP (
    STORE CHILD OF
    CONSUMER_SEGMENT CHILD OF
    TRADING_AREA CHILD OF
    CHAIN
    -- Calendar dimension definition
    create DIMENSION CALENDAR_DIM
    LEVEL MONTH IS CALENDAR_HIERARCHY_TREE.HIERARCHY3_ID
    LEVEL QUARTER IS CALENDAR_HIERARCHY_TREE.HIERARCHY2_ID
    LEVEL WEEK IS CALENDAR_HIERARCHY_TREE.CALENDAR_ID
    LEVEL YEAR IS CALENDAR_HIERARCHY_TREE.HIERARCHY1_ID
    HIERARCHY CALENDAR_ROLLUP (
    WEEK CHILD OF
    MONTH CHILD OF
    QUARTER CHILD OF
    YEAR
    -- Materialized view with just joins needed for other views
    CREATE MATERIALIZED VIEW my_dim_mvw_joins build immediate refresh complete enable query rewrite as
    select product_id, lht.HIERARCHY1_ID, lht.HIERARCHY2_ID, lht.HIERARCHY3_ID, lht.location_id, cht.HIERARCHY1_ID year,
    cht.HIERARCHY2_ID quarter, cht.HIERARCHY3_ID month, cht.calendar_id week, m1, m3, m7, m9
    from retailer_sales_tbl RS, calendar_hierarchy_tree cht, location_hierarchy_tree lht
    WHERE RS.period_id = cht.CALENDAR_ID
    and RS.location_id = lht.location_id
    and cht.CALENDAR_ID in (10,236,237,238,239,608,609,610,611,612,613,614,615,616,617,618,619,1426,1427,1428,1429,1430,1431,1432,1433,1434,1435,1436,1437,1438,1439,1440,1441,1442,1443,1444,1445,1446,1447,1448,1449,1450,1451,1452,1453,1454,1455,1456,1457,1458,1459,1460,1461,1462,1463,1464,1465,1466,1467,1468,1469,1470,1471,1472,1473,1474,1475,1476,1477)
    AND product_id IN (5, 6, 7, 8, 11, 12, 13, 14, 17, 18, 19, 20)
    AND lht.location_id IN (2, 3, 11, 12, 13, 14, 15, 4, 16, 17, 18, 19, 20)
    -- Materialized view which aggregate along calendar dimension
    CREATE MATERIALIZED VIEW my_dim_mvw_calendar build immediate refresh complete enable query rewrite as
    select product_id, HIERARCHY1_ID , HIERARCHY2_ID , HIERARCHY3_ID ,location_id, year, quarter, month, week,
    sum(m1) m1_total, sum(m3) m3_total, sum(m7) m7_total, sum(m9) m9_total,
    GROUPING_ID(product_id, location_id, year, quarter, month, week) dim_mvw_gid
    from my_dim_mvw_joins
    GROUP BY product_id, HIERARCHY1_ID , HIERARCHY2_ID , HIERARCHY3_ID , location_id,
    rollup (year, quarter, month, week);
    -- Materialized view which aggregate along Location dimension
    CREATE MATERIALIZED VIEW my_dim_mvw_location build immediate refresh complete enable query rewrite as
    select product_id, year, quarter, month, week, HIERARCHY1_ID, HIERARCHY2_ID, HIERARCHY3_ID, location_id,
    sum(m1_total) m1_total_1, sum(m3_total) m3_total_1, sum(m7_total) m7_total_1, sum(m9_total) m9_total_1,
    GROUPING_ID(product_id, HIERARCHY1_ID, HIERARCHY2_ID, HIERARCHY3_ID, location_id, year, quarter, month, week) dim_mvw_gid
    from my_dim_mvw_calendar
    GROUP BY product_id, year, quarter, month, week,
    rollup (HIERARCHY1_ID, HIERARCHY2_ID, HIERARCHY3_ID, location_id)
    -- SQL Query Fired (for simplicity have used SUM as aggregation operator for both, but they will be different)
    select product_id, year, HIERARCHY1_ID, HIERARCHY2_ID,
    sum(m1_total) m1_total_1, sum(m3_total) m3_total_1, sum(m7_total) m7_total_1, sum(m9_total) m9_total_1
    from
    select product_id, HIERARCHY1_ID , HIERARCHY2_ID , year,
    sum(m1) m1_total, sum(m3) m3_total, sum(m7) m7_total, sum(m9) m9_total
    from
    select product_id, lht.HIERARCHY1_ID , lht.HIERARCHY2_ID , lht.HIERARCHY3_ID ,lht.location_id, cht.HIERARCHY1_ID year, cht.HIERARCHY2_ID quarter, cht.HIERARCHY3_ID month, cht.calendar_id week,m1,m3,m7,m9
    from
    retailer_sales_tbl RS, calendar_hierarchy_tree cht, location_hierarchy_tree lht
    WHERE RS.period_id = cht.CALENDAR_ID
    and RS.location_id = lht.location_id
    and cht.CALENDAR_ID in (10,236,237,238,239,608,609,610,611,612,613,614,615,616,617,618,619,1426,1427,1428,1429,1430,1431,1432,1433,1434,1435,1436,1437,1438,1439,1440,1441,1442,1443,1444,1445,1446,1447,1448,1449,1450,1451,1452,1453,1454,1455,1456,1457,1458,1459,1460,1461,1462,1463,1464,1465,1466,1467,1468,1469,1470,1471,1472,1473,1474,1475,1476,1477)
    AND product_id IN (5, 6, 7, 8, 11, 12, 13, 14, 17, 18, 19, 20)
    AND lht.location_id IN (2, 3, 11, 12, 13, 14, 15, 4, 16, 17, 18, 19, 20)
    GROUP BY product_id, HIERARCHY1_ID , HIERARCHY2_ID , HIERARCHY3_ID , location_id, year
    ) sales_time
    GROUP BY product_id, year,HIERARCHY1_ID, HIERARCHY2_ID
    This Query rewrites only with my_dim_mvw_calendar. (as saw in Query Plan and EXPLAIN_MVIEW). But we would like it to use my_dim_mvw_location as that has aggregations for both dimensions.

    blackhole001 wrote:
    Hi all,
    I'm trying to make my programmer's life easier by creating a database view for them to query the data, so they don't have to worry about joining tables. This sounds like a pretty horrible idea. I say this because you will eventually end up with programmers that know nothing about your data model and how to properly interact with it.
    Additionally, what you will get is a developer that takes one of your views and see's that of the 20 columns in it, it has 4 that he needs. If all those 4 columns comes from a simple 2 table join, but the view has 8 tables, you're wasting a tonne of resources by using the view (and heaven forbid they have to join that view to another view to get 4 of the 20 columns from that other view as well).
    Ideally you'd write stored routines that satisfy exactly what is required (if you are the database resource and these other programmers are java, .net, etc... based) and the front end developers would call those routines customized for an exact purpose.
    Creating views is not bad, but it's by no means a proper solution to having developers not learn or understand SQL and/or the data model.

  • Bulk collect with Nested loops

    Hi I've a requirement like this
    I need to pull request nos from table a(Master table)
    For every request no I need to pull request details from table b(Detail Table)
    For every request no I need to pull contact details from table c
    For every request no I need to pull customer data table d and I need to create a flat file with that data so I'm using utl_file in normal query criterion because of nested loops it's taking lot of time so I want to use bulk collect with dynamic query option:
    Sample code
    =======
    create or replace procedure test(region varchar2) as
    type tablea_request_typ is table of varchar2(10);
    tablea_data tablea_request_typ;
    type tableb_request_typ is table of varchar2(1000);
    tableb_data tableb_request_typ;
    type tablec_request_typ is table of varchar2(1000);
    tablec_data tablec_request_typ;
    type tabled_request_typ is table of varchar2(1000);
    tabled_data tabled_request_typ;
    stmta varchar2(32000);
    stmtb varchar2(32000);
    stmtc varchar2(32000);
    stmtd varchar2(32000);
    rcura SYS_REFCURSOR;
    rcurb SYS_REFCURSOR;
    rcurc SYS_REFCURSOR;
    rcurd SYS_REFCURSOR;
    begin
    stmta:='select  request_no from tablea where :region'||'='NE';
    stmtb:='select  request_no||request_detail1||request_detail2 stringb  from table b where :region'||'='NE';
    stmtc:='select contact1||contact2||contact3||contact4  stringc from table c where :region'||'='NE';
    stmtd:='select customer1||customer2||customer3||customer4  stringd  from table c where :region'||'='NE';
    OPEN rcura for stmta;
      LOOP
      FETCH rcura BULK COLLECT INTO request_no
      LIMIT 1000;
      FOR  f in 1..request_no.count
    LOOP
    --Tableb
        OPEN rcurb for stmtb USING substr(request_no(f),1,14);
      LOOP
      FETCH rcurb BULK COLLECT INTO tableb_data
    for i in 1..tableb_data.count
    LOOP
    utl_file(...,tableb_data(i));
    END LOOP;
        EXIT WHEN rcurb%NOTFOUND;
      END LOOP;
    -- Tablec
    OPEN rcurc for stmtc USING substr(request_no(f),1,14);
      LOOP
      FETCH rcurb BULK COLLECT INTO tablec_data
    for i in 1..tablec_data.count
    LOOP
    utl_file(...,tablec_data(i));
    END LOOP;
        EXIT WHEN rcurc%NOTFOUND;
      END LOOP;
    -- Tabled
    OPEN rcurd for stmtd USING substr(request_no(f),1,14);
      LOOP
      FETCH rcurd BULK COLLECT INTO tabled_data
    for i in 1..tabled_data.count
    LOOP
    utl_file(...,tabled_data(i));
    END LOOP;
        EXIT WHEN rcurd%NOTFOUND;
      END LOOP;
      END LOOP;
        EXIT WHEN rcura%NOTFOUND;
      END LOOP;
    exception
    when other then
    dbms_output.put_line(sqlerrm);
    end;I 'm using code mentioned above but request nos are repeating as if it's an infinete loop ?for ex if request no is 222 It should run once but here it's running more than once?
    How to pass bind parameters say in my case region?
    Are there any alternate solutions to run it faster apart from using bulk collect?
    Right now I'm using explicit cursor with for loop which is taking lot of time ?so is this better sol?
    Thanks,
    Mahender
    Edited by: BluShadow on 24-Aug-2011 08:52
    added {noformat}{noformat} tags. Please read {message:id=9360002} to learn to format your code/data yourself.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

        Use Parameterized cursor :
    CREATE OR REPLACE PROCEDURE test(region varchar2)
    AS
      type tablea_request_typ is table of varchar2(10);
      type tableb_request_typ is table of varchar2(1000); 
      type tablec_request_typ is table of varchar2(1000);
      type tabled_request_typ is table of varchar2(1000);
      tablea_data tablea_request_typ;
      tableb_data tableb_request_typ;
      tablec_data tablec_request_typ;
      tabled_data tabled_request_typ;
       CURSOR rcura(v_region  VARCHAR2(100))
       IS
       select  request_no from tablea where region = v_region;
       CURSOR rcurb(v_input  VARCHAR2(100))
       IS
       select  request_no||request_detail1||request_detail2 stringb  from table b where request_num = v_input;
       CURSOR rcurc(v_input  VARCHAR2(100))
       IS
       select  select contact1||contact2||contact3||contact4  stringc from table c where request_num = v_input;
       CURSOR rcurd(v_input  VARCHAR2(100))
       IS
       select  select customer1||customer2||customer3||customer4  stringd  from table c where request_num = v_input;
    BEGIN
    OPEN rcura('NE');
    LOOP
        FETCH rcura BULK COLLECT INTO request_no  LIMIT 1000;
        FOR  f in 1..request_no.count
        LOOP
           --Tableb
           OPEN rcurb(substr(request_no(f),1,14));
           LOOP
              FETCH rcurb BULK COLLECT INTO tableb_data
              for i in 1..tableb_data.count
              LOOP
                  utl_file(...,tableb_data(i));
              END LOOP;
              EXIT WHEN rcurb%NOTFOUND;
           END LOOP;
           -- Tablec
           OPEN rcurc (substr(request_no(f),1,14));
           LOOP
              FETCH rcurb BULK COLLECT INTO tablec_data
              for i in 1..tablec_data.count
              LOOP
                 utl_file(...,tablec_data(i));
              END LOOP;
              EXIT WHEN rcurc%NOTFOUND;
           END LOOP;
           -- Tabled
           OPEN rcurd ( substr(request_no(f),1,14) );
           LOOP
              FETCH rcurd BULK COLLECT INTO tabled_data
              for i in 1..tabled_data.count
              LOOP
               utl_file(...,tabled_data(i));
              END LOOP;
              EXIT WHEN rcurd%NOTFOUND;
           END LOOP;
      END LOOP;
    EXIT WHEN rcura%NOTFOUND;
    END LOOP;
    EXCEPTION
    WHEN OTHERS THEN
       dbms_output.put_line(dbms_utility.format_error_backtrace);
    END;
    /Hope this helps. If not, post your table structures...

  • Executing nested query contains ORDER BY:Help Needed

    I have a database in ORACLE 8.0 enterprise
    edition in HP-UX. I am trying to execute the following query
    "select * from ( select * from temptable order by value desc) where rownum < 5"
    and I am getting the following error
    "missing right parenthesis"
    This syntax is given in the Oracle user guide
    under sql commands section and it is not
    working.
    Similar query is working on Oracle 8.1 running on Win NT.
    Does any body throw some light.
    Thanks in advance
    -raj

    Your query works fine in Oracle 8i:
    SELECT *
    FROM (SELECT *
    FROM temptable
    ORDER BY value DESC)
    WHERE ROWNUM < 5;
    However, prior to Oracle 8i, in Oracle 8.0, it is not allowed to have an ORDER BY clause within a nested query. So, in Oracle 8.0, a query like the above cannot work. However, the following, with the ORDER BY clause in the outer query will work:
    SELECT *
    FROM temptable a
    WHERE 5 >=
    (SELECT COUNT (*) + 1
    FROM temptable b
    WHERE b.value > a.value)
    ORDER BY a.value DESC;
    null

  • Report region with sql query

    Hi
    I have a report region with sql query. There are two regions in page. On top of page, user enters data and after that second region show enterd data which is report region
    based on sql query.
    Now,when this page is opned, as user had not entered any thing, report region shows "no data found" message. Is it possible to remove that message or
    may i conditionally disaply report region i.e if data is inserted then only report region is dispalyed.
    Thanks

    >
    i was trying with select count(1) in expression.
    >
    Just for your info, COUNT() (without any grouping obviously) with always return 1 row. If there are no result for the query then 1 row will be returned with a value of zero - so there are results returned.
    Secondly, why were you using COUNT(1) rather than COUNT(*)? That is is faster is a very common misconception and not true. If you need to know how many rows have been returned, use COUNT(*). If you need to take nulls into account (ie. not include them in your count) then use COUNT(column_name) and name the column that you are interested in specifically.
    Cheers
    Ben

  • Showing column value as counter in sql query - report

    I created a classic report with search bar based on an sql query. I would like to show the "notes" column in this query using some sort of counter and as a hyperlink to another section on the page (same idea as footnotes in a book). So if I have 10 rows and 5 have "notes". I should show 1,2,3,4,5 in the notes column for those rows and the number gets displayed as a link to another section listing the notes 1 through 5.
    I was thinking of creating a hidden page item as the counter with value of 0 and then in my query doing counter+1 but i'm not sure how to do this or if i can do that...
    If anyone can help or have any other ideas I would really appreciate it!!
    Thanks,
    Hindy

    Well, I'm doing this in VB and the subquery is dynamic. I'm passing an ADO recordset to a routine that sets up a listview to display the results. The number of columns selected can vary. My idea was to size the columns appropriately based on the size of the data. Within the display routine I could:
    sql = "SELECT "
    for i = 0 to oRS.Fields.Count - 1
    sql = sql & "MAX(LENGTH(" & i & ")), "
    next 'i
    sql = sql & "FROM (" & oRS.Source & ")"

  • What is wrong With My Query

    Pleas what is wrong with this query
         select h.business_unit_id bu, h.edi_sequence_id seq, d.edi_det_sequ_id dseq, s.edi_size_sequ_id sseq, h.po_number po, h.total_unit tUnit, h.total_amount tDollar, s.quantity qty, s.unit_price price,
    (select (case when count(*) = 0 then 'N' else 'Y' end)
    from(select s.business_unit_id, s.edi_sequence_id, s.edi_det_sequ_id, s.edi_size_sequ_id
    from sewn.nt_edii_purchase_size s
    where s.business_unit_id='01'
    and s.edi_sequence_id = '168420'
    and (s.edi_sequence_id, s.edi_det_sequ_id, s.edi_size_sequ_id) not in
    (select edi_sequence_id, edi_det_sequ_id, edi_size_sequ_id
    from sewn.nt_edii_po_det_error
    where business_unit_id = '01'
    and edi_sequence_id='168420'
    and error_code in(select error_code
    from sewn.nt_edii_error_codes
    where severity='CR'))))eligible
    from sewn.nt_edii_purchase_size s, sewn.nt_edii_purchase_det d,
    sewn.nt_edii_purchase_hdr h
    where h.business_unit_id = '01'
    and h.edi_sequence_id = '168420'
    and h.business_unit_id = d.business_unit_id
    and h.edi_sequence_id = d.edi_sequence_id
    and d.business_unit_id = s.business_unit_id
    and d.edi_sequence_id = s.edi_sequence_id
    and d.edi_det_sequ_id = s.edi_det_sequ_id
    group by h.business_unit_id, h.edi_sequence_id, d.edi_det_sequ_id,
    s.edi_size_sequ_id,h.po_number, h.total_unit, h.total_amount, s.quantity,s.unit_price

    Never mind, I got it working

  • Need help in 'WITH CLAUSE' Query

    Hello Gurus,
    I am trying to calculate the count of distinct members for each provid.
    I am using the with clause to get information regarding the provid.
       WITH T AS
      (SELECT a.UD_ID MRR_ID,
                            A.UD_LASTNAME LAST_NAME,
                            A.UD_FIRSTNAME FIRST_NAME,
                            COUNT(DISTINCT DP.PA_PROVIDERID) PROVIDERS_ASSIGNED
                       FROM (SELECT UD.UD_ID,
                                    UD_LASTNAME,
                                    UD_FIRSTNAME
                               FROM USER_DETAILS       UD,
                                    MAP_USERS_TO_ROLES MR
                              WHERE MR.MUR_UR_ID_REF = 1000
                                AND MR.MUR_UD_ID_REF = UD.UD_ID) A,
                            D4C_PROVIDER_ASSIGNMENT DP
                      WHERE A.UD_ID = DP.PA_ASSIGNEDTO
                      AND dp.pa_status ='A'
                      GROUP BY A.UD_ID,
                               A.UD_LASTNAME,
                               A.UD_FIRSTNAME
                      ORDER BY 3 DESC)    OUTPUT of just above query without WITH clause.
    MRR_ID     LAST_NAME     FIRST_NAME     PROVIDERS_ASSIGNED
    1229    mrrTest         mrrTest         4
    1228    mrr2Last        mrr2First       5
    1230    mrr1Last        mrr1First       7
    1226    Panwar          SIngh           1
    1181    MRRLast         MRRTest         4
    1221    One             MRR             1
    1322    Thakuria        Bibhuthi        2I am creating this and get all the information to show on front end. Now I want to calculate the no of members as per the providers assigned for each MRR_ID
    Below query show the no of members for all the providers assigned to a provider.
    ex:
    SELECT * FROM (   
    SELECT COUNT(DISTINCT dmpc_hicn) countmember
    FROM D4C_HICN_PROVIDER_claims  a WHERE trim(DPMC_PROVIDER_NO) IN 
    (SELECT trim(pa_providerid)
       FROM d4c_provider_assignment
       WHERE pa_assignedto = 1181  (mrr_id)    --here i have use the mrrid from with clause and get the member count with all the columns coming from WITH CLAUSE.
       AND pa_roleid = 1000
       AND PA_STATUS ='A'
    GROUP BY a.dmpc_ss_id_ref)Right now I am using materialized view i dont wanna use the same..
    I am sending the materialized view code as well what i am doing ..
    ( SELECT SUM(member_count)member_count_bynpi ,mrr_id  FROM (
    (SELECT count(DISTINCT hp.dmpc_hicn) member_count,hp.DMPC_SS_ID_REF ,a1.ud_id mrr_id FROM  D4C_HICN_PROVIDER_claims hp ,
    (SELECT   a.UD_ID ,DP.PA_PROVIDERID
         FROM (SELECT UD.UD_ID, UD_LASTNAME, UD_FIRSTNAME
                 FROM USER_DETAILS UD, MAP_USERS_TO_ROLES MR
                WHERE MR.MUR_UR_ID_REF = 1000
                  AND MR.MUR_UD_ID_REF = UD.UD_ID) A,
              D4C_PROVIDER_ASSIGNMENT DP
        WHERE A.UD_ID = DP.PA_ASSIGNEDTO
        AND dp.pa_status ='A'
        /*AND dp.PA_ASSIGNEDTO = 1221*/) a1
        WHERE trim(a1.PA_PROVIDERID) = trim(hp.dpmc_provider_no)
        GROUP BY a1.ud_id,hp.DMPC_SS_ID_REF))
        GROUP BY mrr_id)Please help me to write the code with the materialized view. Thanks in Advance.
    Kind regards,
    UP
    Edited by: BluShadow on 22-Aug-2011 07:58
    fixed {noformat}{noformat} tags.  Please use lowercase "code" rather than uppercase "CODE" in the tags.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    Probably, this may help
    WITH T1 as(
               SELECT UD.UD_ID,
                      UD_LASTNAME,
                      UD_FIRSTNAME
                FROM USER_DETAILS UD, MAP_USERS_TO_ROLES MR
                WHERE MR.MUR_UR_ID_REF = 1000
                AND MR.MUR_UD_ID_REF = UD.UD_ID)
          T2 as (SELECT a.UD_ID ,DP.PA_PROVIDERID
                 FROM T1 A, D4C_PROVIDER_ASSIGNMENT DP
                 WHERE A.UD_ID = DP.PA_ASSIGNEDTO
                 AND dp.pa_status ='A')
           T3 as(SELECT count(DISTINCT hp.dmpc_hicn) member_count,
                              hp.DMPC_SS_ID_REF ,
                               a1.ud_id mrr_id
                  FROM T2 A1 ,D4C_HICN_PROVIDER_claims hp
                  WHERE trim(a1.PA_PROVIDERID) = trim(hp.dpmc_provider_no)
                  GROUP BY a1.ud_id,hp.DMPC_SS_ID_REF)
    SELECT SUM(member_count)member_count_bynpi ,mrr_id from T3
    GROUP BY mrr_id

Maybe you are looking for

  • Looking for help building app! Great idea!

    Hey, I have a great idea for a really fun game that could draw attention to alot of iOS users and soon become very popular. I have done some browsing in the App Store and the idea i have is not yet there. The reason I am reaching out to the forums is

  • Problem with Submit Button in Adobe Forms Central

    I have a PDF form that I uploaded to Adobe Forms Central.  I created the fillable fields & the submit button in Forms Central.  I have several documents like this.  All have worked in the past.  Today on my latest file, the submit button doesn't alwa

  • How would someone go about searching or finding songs from a certain year ?

    I would like to find songs and albums from my high school years 1980 to 1983. What's the best way to find only songs from these years within the itunes store ? The search engine doesn't have any way to do this as far as i know. This feature would be

  • March cannot be displayed in Calendeer

    Sobald man versucht, den März 2013 in der Monatsansicht anzuzeigen, verabschiedet sich die Kalender-App If you try to show MARCH in the Calender App the App is breaking down.

  • 40000 files and 600 playlists need moving to a new computer

    I'm overwhlemed with internet advice and it's all a bit too general. I need specific advice on transferring 40,000+ tracks and 600+ playlists to a new computer. Old setup: 40,000+ tracks on an external hard drive (so all files are recognised as "F:\.