Difference of 2 queries

Will the below query return the difference of the "sum(e.gl_fig)" column from both the queries ?
select (select sum(e.gl_fig) from rm_gl e where e.as_on_dt <= trunc(to_date('30-NOV-2011'),'Q')- 1) - (select sum(e.gl_fig) from rm_gl e where e.gl_id in (211,212,213,214,215,216,217) and e.as_on_dt = to_date('30-NOV-2011')) current_quarter_amount from dual

Have you tried it? Did it work?
It looks like it probably should work, but not easy to read ;-)
(Would be nice if you had formatted the code and put it within tags...)                                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • Difference between the queries - help needed.

    I have three tables Plan_Zip,Service_Zip,Plan_Info
    Plan_Zip is the parent table and referenced by Service_Zip
    and Service_Zip is referenced by Plan_Info.
    I have this query:
    select
         sz.ts_nbr,pz.packages_qty,pz.stops_qty
    from
         plan_zip pz, service_zip sz, plan_info pi
    where
         pi.plan_run_nbr = sz.plan_run_nbr and
         sz.service_run_nbr = pz.service_run_nbr and     
         pi.day_plan_nbr = 43027 and
         pi.run_type_nbr = 0 and
         sz.ts_nbr = 1 or sz.ts_nbr = 2
    When I am running the query I am getting so many rows which are identical,
    but when I modified the above query as:
    select
         sz.ts_nbr,pz.packages_qty,pz.stops_qty
    from
         plan_zip pz, service_zip sz, plan_info pi
    where
         pi.plan_run_nbr = sz.plan_run_nbr and
         sz.service_run_nbr = pz.service_run_nbr and     
         pi.day_plan_nbr = 43027 and
         pi.run_type_nbr = 0 and
         (sz.ts_nbr = 1 or sz.ts_nbr = 2)
    I am getting the correct results.
    Please explain me the difference between the above two queries.
    Regards
    Raghu

    Look at the below example
    SQL> create table t
      2  as
      3  select level no, level no1, 0 no2
      4    from dual
      5  connect by level <= 5
      6  /
    Table created.
    SQL> select * from t
      2  /
            NO        NO1        NO2
             1          1          0
             2          2          0
             3          3          0
             4          4          0
             5          5          0
    SQL> select *
      2    from t
      3   where no = 1
      4     and no1 = 1
      5      or no2 = 0
      6  /
            NO        NO1        NO2
             1          1          0
             2          2          0
             3          3          0
             4          4          0
             5          5          0Here what the where condition is telling is no should be 1, no1 should be 1 or no2 is 0. you can read it like this.
    if (no = 1 and no1 = 1) or (no2 = 0)
    then
         true ;
    else
         false;
    end if;so what i does is no2 = 0 is satisfied by all the rows and hence all the rows are returned.
    Next...
    SQL> select *
      2    from t
      3   where no = 1
      4     and (no1 = 1 or no2 = 0)
      5  /
            NO        NO1        NO2
             1          1          0This can be read like this.
    if (no = 1) and (no1 = 1 or no2 = 0)
    then
         true ;
    else
         false;
    end if;Here no = 1 is a must satisfy condition. Once that is satisfied then no1 can be 1 or no2 can be 0 which ever is
    satisfied consider that. So the first condition no=1 is satisfied by only one record and hence that alone is returned.
    Thanks,
    Karthick.

  • Difference between to queries while using UPPER

    One confusion..
    I see this, most of the places..
    Select * from tableA
    Where upper(colA) = upper(p_parameter);
    Or
    l_variable := upper(p_parameter);
    Select * from tableA
    Where upper(colA) = l_variable;
    Which among the Above will Perform well ..........

    C:\Documents and Settings\Girish Sharma>sqlplus
    SQL*Plus: Release 10.2.0.1.0 - Production on Wed Aug 19 15:52:28 2009
    Copyright (c) 1982, 2005, Oracle.  All rights reserved.
    Enter user-name: scott/tiger
    Connected to:
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
    With the Partitioning, OLAP and Data Mining options
    SQL> set autotrace traceonly statistics;
    SQL> select ename from emp where upper(ename)='JAMES';
    Statistics
              1  recursive calls
              0  db block gets
              8  consistent gets
              0  physical reads
              0  redo size
            411  bytes sent via SQL*Net to client
            381  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
              1  rows processed
    SQL> exitRelogin:
    C:\Documents and Settings\Girish Sharma>sqlplus
    SQL*Plus: Release 10.2.0.1.0 - Production on Wed Aug 19 15:54:31 2009
    Copyright (c) 1982, 2005, Oracle.  All rights reserved.
    Enter user-name: scott/tiger
    Connected to:
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
    With the Partitioning, OLAP and Data Mining options
    SQL> set autotrace traceonly statistics;
    SQL> VARIABLE INPUT VARCHAR2(50);
    SQL> EXEC :INPUT := 'james';
    PL/SQL procedure successfully completed.
    SQL> select ename from emp where upper(ename)=upper(:input);
    Statistics
              0  recursive calls
              0  db block gets
              8  consistent gets
              0  physical reads
              0  redo size
            411  bytes sent via SQL*Net to client
            381  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
              1  rows processedOnly one difference in recursive calls, so it means both are almost same.
    Girish Sharma

  • Outer join: difference between two queries

    Below two queries that should give the same results in my opinion. I want all the records from u_protocol and only the value of pval.u_protocol_variable_value if present.
    Why does the outer join in query2 doesn't work like in query1?
    Query1:
    select p.u_protocol_id, i.u_protocol_variable_value
    from lims_sys.u_protocol p,
       select pval.u_protocol_id, pval.u_protocol_variable_value
       from lims_sys.u_protocol_variable pvar, lims_sys.u_protocol_value_user pval
       where pvar.u_protocol_variable_id = pval.u_protocol_variable_id
       and pvar.name = 'VALUE_Protocol_Group'
    ) i  
    where p.u_protocol_id  = i.u_protocol_id (+)
    Query2:
    select prt.u_protocol_id, pval.u_protocol_variable_value
    from lims_sys.u_protocol prt, lims_sys.u_protocol_variable pvar, lims_sys.u_protocol_value_user pval
    where pvar.u_protocol_variable_id = pval.u_protocol_variable_id
    and prt.u_protocol_id = pval.u_protocol_id (+)
    and pvar.name = 'VALUE_Protocol_Group'

    In the first query restriction pvar.name = 'VALUE_Protocol_Group' is limited to your inline view. So when you do a outer join with the u_protocol table you will get the number of records which are there in the u_protocol table.
    But when you gave the restriction pvar.name = 'VALUE_Protocol_Group' outside the inline view, the restriction was based on the resultset as a whole. So you will get only those records which have pvar.name = 'VALUE_Protocol_Group' condition satisfied.
    Hope the following illustration helps:
    SQL> CREATE TABLE TEST_TAB
      2  AS
      3  SELECT level col_1, chr(65+level-1) col_2 FROM Dual
      4  CONNECT BY LEVEL <= 10
      5  /
    Table created.
    SQL> SELECT * FROM TEST_TAB
      2  /
         COL_1 COL_
             1 A
             2 B
             3 C
             4 D
             5 E
             6 F
             7 G
             8 H
             9 I
            10 J
    10 rows selected.
    SQL> CREATE TABLE TEST_TAB_B
      2  AS
      3  SELECT level col_3, chr(65+level-1) col_4 FROM Dual
      4  WHERE Level NOT IN (2,3,4)
      5  CONNECT BY LEVEL <= 10
      6  /
    Table created.
    SQL> SELECT * FROM TEST_TAB_B
      2  /
         COL_3 COL_
             1 A
             5 E
             6 F
             7 G
             8 H
             9 I
            10 J
    7 rows selected.
    SQL> SELECT a1.col_1, a1.col_2, a2.col_3, a2.col_4 FROM TEST_TAB a1,
      2  TEST_TAB_B a2
      3  where a1.col_1 = a2.col_3(+)
      4  order by a1.col_1
      5  /
         COL_1 COL_      COL_3 COL_
             1 A             1 A
             2 B
             3 C
             4 D
             5 E             5 E
             6 F             6 F
             7 G             7 G
             8 H             8 H
             9 I             9 I
            10 J            10 J
    10 rows selected.Notice the output without any extra conditions: You will get all the values from TEST_TAB and matching records from TEST_TAB_B. Non-matching records are outputed as NULL.
    Following Query is resemblence to your first query
    SQL> SELECT a1.col_1, a1.col_2, a2.col_3, a2.col_4 FROM TEST_TAB a1,
      2  (SELECT * FROM TEST_TAB_B where col_4='A') a2
      3  where a1.col_1 = a2.col_3(+)
      4  order by a1.col_1
      5  /
         COL_1 COL_      COL_3 COL_
             1 A             1 A
             2 B
             3 C
             4 D
             5 E
             6 F
             7 G
             8 H
             9 I
            10 J
    10 rows selected.Here TEST_TAB_B Table is restricted with a condition which will restrict the inline view to have only one record. So when you outer join the inline view you will get output as shown above.
    The following query resembles to your second query.
    SQL> SELECT a1.col_1, a1.col_2, a2.col_3, a2.col_4 FROM TEST_TAB a1,
      2  TEST_TAB_B a2
      3  where a1.col_1 = a2.col_3(+)
      4  and a2.col_4 = 'A'
      5  order by a1.col_1
      6  /
         COL_1 COL_      COL_3 COL_
             1 A             1 A
    1 row selected.
    SQL> DROP TABLE TEST_TAB_B
      2  /
    Table dropped.
    SQL> DROP TABLE TEST_TAB
      2  /
    Table dropped.
    SQL> To understand this lets break up the resultset.
    Resultset brought by join condition would be something like :
        COL_1 COL_      COL_3 COL_
             1 A             1 A
             2 B
             3 C
             4 D
             5 E             5 E
             6 F             6 F
             7 G             7 G
             8 H             8 H
             9 I             9 I
            10 J            10 JAgreed?
    Now when you add the extra condition a2.col_4 = 'A' thecondition will act upon the above resultset there by restricting the records to:
         COL_1 COL_      COL_3 COL_
             1 A             1 AHope this helps.
    Regards,
    Jo

  • Difference between these queries

    Hi,
    I have two tables table1 and table2. Both have a common column say for ex. col1
    I tried to find the rows in table1 where there is no corresponding value for col1.
    My query is
    Select * from table1 a where a.col1 not in (select b.col1 from table2 b);
    This returned me nothing.
    But when my co-worker executed a query like this
    select a.col1 from table1 a
    minus
    select b.col1 from table2 b;
    This gave us the results. How is both of them different and how to know where to use what?

    Hi,
    where   a.col1 not in (select b.col1 from table2 b);will never evaluate to TRUE if there are NULLs in table2.col1.
    Remember that SQL uses three-valued logic.
    Expressions such as x IN (y) can be TRUE, FALSE, or UNKNOWN.
    Since x = NULL is UNKNOWN (even if x itself IS NULL), then x IN (y), where y is a list or a sub-query, will be either TRUE or UNKNOWN if y contains NULL.
    So x NOT IN (y) will be either FALSE or UNKNOWN (if y contains NULL).
    To be practical, NOT IN sub-queries usually need to guarantee that they will not return NULL rows, e.g.
    WHERE   a.col1 NOT IN
            SELECT  col1
            FROM    table2
            WHERE   col1 IS NOT NULL
            )Repeat: this applies only to NOT IN sub-queries.
    IN sub-queries behave the way most people find intuitive.

  • Whats the difference between 2 Queries

    Hi Guru!!
    I have following 2 queries. 2nd query serves my purpose,But first query cannot.
    I dont understant, how the 2nd query works.Please explain if you can.
    1st query
    SELECT item_name, item_no
    FROM mmv_itemstock
    WHERE store_id = NVL(:STORE_ID,store_id)
    AND category_no = NVL(:category_no,category_no)
    AND subcat_no = NVL(:subcat_no,subcat_no);
    2nd Query
    SELECT item_name, item_no
    FROM mmv_itemstock
    WHERE NVL(store_id,'N') = NVL(:STORE_ID,NVL(store_id,'N'))
    AND NVL(category_no,'N') = NVL(:category_no,NVL(category_no,'N'))
    AND NVL(subcat_no,'N') = NVL(:subcat_no,NVL(subcat_no,'N'));
    Thanks in advance
    Mokarem
    = = = = =

    I like LNNVL, but it does not deliver the right resultIt also depends on your interpretation of the OPs requirement:
    SQL> select 1 from dual where NVL(null,'N') = NVL('N',NVL(null,'N'));
             1
             1
    SQL> select 1 from dual where decode(null,'N',1)=1;
    no rows selected
    SQL> select 1 from dual where lnnvl(null<>'N');
             1
             1
    SQL> select 1 from dual where ''='N' or ('' is null or 'N' is null);
             1
             1

  • Difference between two queries for no client installed

    I have created a collection for all discovered computers with no client installed using the following query:
    select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where SMS_R_System.Client is null
    If I go to Monitoring -> Client Status -> Client Activity and click on the link next to the pie chart for no clients installed I get a completely different result and they neither query contains the same computers as each other.
    Anyone know what the exact query the link in the monitoring section is using and why the results between the two are completely different?
    If would expect them to match up or at the very least that my first query should be the source of truth.

    If I use:
    select SMS_R_SYSTEM.ResourceID,SMS_R_SYSTEM.ResourceType,SMS_R_SYSTEM.Name,SMS_R_SYSTEM.SMSUniqueIdentifier,SMS_R_SYSTEM.ResourceDomainORWorkgroup,SMS_R_SYSTEM.Client from SMS_R_System where SMS_R_System.Client is null OR SMS_R_System.Client = 0
    and use the same limiting collection as the built in monitoring query  "All Desktop and Server Clients" I actually get 0 results from the query.  If I use "All Systems" as the limiting collection I still only get the same results
    that I do with out also querying for "equals 0" as well.
    I read one article that said that "equals 0" actually shows you the clients had the CCM client but it was uninstalled where "is Null" returns systems that never had the CCM client.
    I don't know if this is accurate but it doesn't explain why a built in monitoring query would return inaccurate results.  It only returns a fraction of the non-client systems that the above query returns and as mentioned, the systems returned in one
    are not included in the other.

  • Difference in queries

    can someone let me know difference between following queries.. why they return different results for the 4th column.
    SELECT      CUSTOMER.BILL_CYCLE,
    CUSTOMER.PARTITION_ID,
    COUNT(*),
    (select count(1)
    from Subscriber S , Customer C
    where S.customer_id = C.customer_id
    and S.sub_status='A'
    and C.BILL_CYCLE = Customer.BILL_CYCLE
    and C.PARTITION_ID = CUSTOMER.PARTITION_ID)
    FROM CUSTOMER
    group by BILL_CYCLE, PARTITION_ID
    SELECT bill_cycle, partition_id, COUNT (*),SUM (subs_per_customer)
    FROM (SELECT /*+ use_hash(c s) parallel(c,4) */
    bill_cycle, partition_id, c.customer_id,
    COUNT (DECODE (s.subscriber_no, NULL, 0, 1)) subs_per_customer
    FROM subscriber s, customer c
    WHERE s.customer_id(+) = c.customer_id AND s.sub_status(+) = 'A'
    GROUP BY bill_cycle, partition_id, c.customer_id)
    GROUP BY bill_cycle, partition_id

    Try something like this. And just dont say its slow. Paste the explain plan and the table structure also.
    SQL> create table customer(bill_cycle number, partition_id number, customer_id number);
    Table created.
    SQL> insert into customer values (1,1,1);
    1 row created.
    SQL> insert into customer values (1,1,2);
    1 row created.
    SQL> insert into customer values (1,1,3);
    1 row created.
    SQL> insert into customer values (1,1,4);
    1 row created.
    SQL> insert into customer values (1,1,5);
    1 row created.
    SQL> create table subscriber(customer_id number, sub_status char(1));
    Table created.
    SQL> insert into subscriber values (1,'A');
    1 row created.
    SQL> insert into subscriber values (2,' ');
    1 row created.
    SQL> insert into subscriber values (3,'A');
    1 row created.
    SQL> insert into subscriber values (4,' ');
    1 row created.
    SQL> insert into subscriber values (5,'A');
    1 row created.
    SQL> commit
      2  /
    Commit complete.
    SQL>  SELECT bill_cycle,
      2     partition_id,
      3     count(*) cnt,
      4     sum(cnt) sm
      5     FROM (SELECT c.bill_cycle,
      6             c.partition_id,
      7             (SELECT count(1)
      8                FROM subscriber s
      9               WHERE s.customer_id  = c.customer_id
    10                 AND s.sub_status   = 'A') cnt
    11        FROM customer c)
    12    GROUP BY bill_cycle,
    13     partition_id
    14  /
    BILL_CYCLE PARTITION_ID        CNT         SM
             1            1          5          3Edited by: Karthick_Arp on Oct 15, 2008 11:59 PM
    Corrected the typo

  • XML queries in ORACLE 10gR1 vs ORACLE 10gR2

    Hi
    in the research project where I'm involved in, we have two databases. One is the test database, upgraded recently in ORACLE 10gR2 and the production database in ORACLE 10gR1.
    We have the same table with the same data in both test and production database.
    I can run successfully the query and get result in test db ORACLE 10gR2:
    SELECT XMLQuery('declare namespace
    mpeg7="urn:mpeg:mpeg7:schema:2001";for $i in /mpeg7:Mpeg7
    return $i' PASSING xmlcolumn RETURNING CONTENT) FROM
    XMLTable WHERE existsNode(xmlcolumn,
    '//@id="2005"',
    'xmlns="urn:mpeg:mpeg7:schema:2001"') = 1;
    but if I try the same query in production db ORACLE 10gR1, I get the error
    return $i' PASSING xml_column RETURNING CONTENT) FROM
    FEHLER in Zeile 3:
    ORA-00907: missing right parenthesis
    Is there any difference in the queries syntax between R1 and R2?
    What should I change in my query?
    Please help. I’m really facing with some problems with XML storage and retrieve.
    Any kind of help will be appreciable
    Best regards,
    Evanela

    Hi Evanela,
    XQuery is available from 10gR2 and higher - the XQuery functionality
    is just not available in 10gR1 ...
    Does this help ...?
    -Carsten

  • Comparing 2 SQL queries in TOAD

    Hi,
    Is there any way to compare 2 sql queries using TOAD?
    I.e. if there are 2 sql queries and i want to know where exactly is the difference in the queries, then is it possible to know using TOAD?
    Thanks in advance
    --kumar                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Oracle has more than enough on its plate dealing with its existing product line and integrating the product suites.
    There is no real need to use thrid party tools.
    Re: Oracle Third Party Tools and Oracle Database
    Adith

  • Multiple Queries on Workbook not independant

    Hi all,
    I have a Workbook with 5 sheets. 5 Data Providers - one per sheet, all based on the same query.
    Difference between Sheets/Queries is mostly Filter criteria and minimal navigation.
    When I have refreshed my workbook, everything seems fine. But as soon as I want to change my drill-down, or swap characteristics, the whole workbook gets confused.
    It seems that any changes I make on Sheet1 for example, applies to sheet 2-5 as well. Even if they are all based on different Data Providers. (Saving queries as different Views did the same.)
    It seems the problem is with SAP`s Data provider not being unique on sheets. Example:
    On the workbook, go to the properties on the Grid > General...
    It shows the Dataprovider, and range. This range is like $A$1:$F$15
    And there is no refrence to a sheet...It should be SHEET1!$A$1:SHEET1!$F$15
    I assume this could be the only reason that my data providers are affecting each other even though they are on different sheets...?
    Any work arounds?

    Hi Mr G,
    Thanks...
    As per your reply, there are only 5 Analysis Grids on my workbook. But each has an unique Data Provider against it..... There is no other object/item in the workbook. No Data Provider is used twice anywhere...
    Let me try and explain again what I just retested.
    Lets say there are two sheets with two grids, one on each. They look the same, as they are both from the same query, but are sourcing from two different Data Providers.
    I refresh both, with two different variants.
    I right click on the first sheet`s grid to apply a filter on a characteristic. Nothing happens. I go look at sheet two, and found my filter applied there! The same if I apply a change on sheet two, it happens on sheet one.
    Now...I go back to the start....but instead of putting the two grids on the same positions on their sheets...I move grid 2 on sheet 2 far right. (So their excel grid positions are not the same)
    Now when I apply the same filter on sheet one, sheet one changed, and sheet 2 remained unaffected...
    Is it because there are 5 Data providers sourcing from one query? I have tried with views and the same happens....
    Edited by: Martin Taylor on Nov 25, 2008 7:56 AM

  • BOBJ - BW  "Error getting hierarchies for dimension... "

    Im still whitout a solution for this problem, however we have found a difference between the queries that work and the queries that dont work. The difference is in the hierarchies type but we dont know what is the problem exactly.
    Does anyone know if there is an specyfic type of hierarchie that we need to use???
    Regards

    Hi,
    I wonder why you are not using the BEx / BICS connection ?  (instead of the old OLAP .unv)
    the process flow for generating a universe would include the following SE37 function modules:
    BAPI_MDPROVIDER_GET_CATALOGS
    BAPI_MDPROVIDER_GET_CUBES
    BAPI_MDPROVIDER_GET_DIMENSIONS
    BAPI_MDPROVIDER_GET_HIERARCHYS
    You should test these in BW .
    It may actually be an authorization issue - perhaps your logon doesn't have infoobject authorizations for 0Plant?
    Regards,
    Henry
    p.s. a quick Note search suggests : 1565615 - Error when creating a Universe from BEx: "A runtime exception has occurred. (Error getting levels for hierarchy ( dimension : Unknown error)"
    --> "Business Objects Personalization objects" R21K900693 transport has not been loaded properly in the BW system, transaction STMS shows this trasport not loaded.

  • Sql profiles in 11.1.0.7

    We just upgraded from 10.1.0.3 to 11.1.0.7 and some very complex queries are running slower. When I check the plans in a non-production 11g database, the join orders are slightly different. I also have traces from my 10g production database and that I loaded into a sql tuning set in production. I am running the sql tuning advisor. When I get a recommendation to use the old plan, I implement it in the 10.2.0.5 Oracle Enterprise manager grid control.
    How do I tell the sql_id of the sql profile? Is it part of the name? So if I look in dba_sql_profiles and see
    SYS_SQLPROF_012a8f339c4b0001
    Is the last part the sql_id? When I search on that value, I do not see it in v$sql. It does not appear that my queries are using the sql profile. So there might a slight difference from these queries (space maybe) than the ones I have. How do I confirm that my queries are using a sql profile as well?

    Dear user11990507,
    I do think that the value "012a8f339c4b0001" is nothing to do with the SQL_ID in the v$sql fixed view. It can be generated based on an algorithm like generating SQL_IDs. That is an internal information and i really don't know much about it.
    You can also accept, alter or drop an SQL profile with the below commands;
    DECLARE my_sqlprofile_name VARCHAR2(30);
    BEGIN my_sqlprofile_name := DBMS_SQLTUNE.ACCEPT_SQL_PROFILE (task_name => 'my_sql_tuning_task', name => 'my_sql_profile', force_match => TRUE);
    END;
    BEGIN
    DBMS_SQLTUNE.ALTER_SQL_PROFILE(name => 'my_sql_profile', attribute_name => 'STATUS', value => 'DISABLED');
    END;
    BEGIN
    DBMS_SQLTUNE.DROP_SQL_PROFILE(name => 'my_sql_profile');
    END;
    DBA_SQL_PROFILES;
    http://download.oracle.com/docs/cd/B28359_01/server.111/b28320/statviews_4256.htm#REFRN23477
    Check the SQL_TEXT column for you particular SQLs.
    Hope That Helps.
    Ogan

  • How to find bottleneck in pivot query

    I have the following table and query I am running against that table.
    CREATE TABLE StagingTable(
    DateKey int NOT NULL,
    VersionNumber smallint NOT NULL,
    SetID varchar(10) NULL,
    ClassID char(5) NULL,
    VariableName varchar(50) NULL,
    VariableDescription varchar(255) NULL,
    PeriodNumber int NULL,
    PeriodData decimal(18, 6) NULL,
    Column1 varchar(50) NULL,
    Column2 varchar(50) NULL,
    Column3 varchar(50) NULL,
    Column4 varchar(50) NULL,
    Column5 int NULL,
    Column6 varchar(25) NULL,
    Column7 int NULL,
    Column8 int NULL,
    Column9 varchar(50) NULL,
    Column10 varchar(50) NULL,
    Column11 varchar(50) NULL,
    Column12 int NULL,
    RowNumber int NULL
    GO
    WITH cte as (
    SELECT
    DateKey ,
    VersionNumber ,
    SetID ,
    ClassID ,
    VariableName ,
    PeriodNumber ,
    PeriodData
    from StagingTable
    SELECT
    DateKey ,
    VersionNumber ,
    SetID ,
    ClassID ,
    VariableName,
    [0], [1], [2], [3], ,,,, [360]
    from cte
    pivot (SUM(PeriodData)
    FOR PeriodNumber IN (
    [0], [1], [2], [3], ..., [360]
    ) as pvt;
    CREATE UNIQUE NONCLUSTERED INDEX IX_StagingTable ON dbo.StagingTable
    DateKey,
    VersionNumber,
    SetId,
    ClassID,
    VariableName,
    PeriodNumber
    INCLUDE ([PeriodData])
    I have about 5 million rows in StageTable and the pivot query returns 32,000 rows.  It takes about 3 and a half minutes to run this query, whether I am outputting the results to the results window in SSMS or selecting into a new table.
    I checked the execution plan for this query (outputting to results window) and the only operation that takes any time is the non-clustered index scan (84% with Stream aggregate showing 14%).
    Here are the things I compared this to.  I ran a select from this table using just the columns in the index. The results returned in less than one minute and as expected the most expensive operation (100%) was the non-clustered index scan. 
    By the way, a select into returned almost immediately.
    If I take the pivot results (after a select into) and create a new table by select into, it takes almost no time for the query to finish.
    I did an estimated execution plan on these three queries (where PivotTable is a dump of the pivot query into a heap):
    WITH cte as (
    SELECT
    DateKey ,
    VersionNumber ,
    SetID ,
    ClassID ,
    VariableName ,
    PeriodNumber ,
    PeriodData
    from StagingTable
    SELECT
    DateKey ,
    VersionNumber ,
    SetID ,
    ClassID ,
    VariableName,
    [0], [1], [2], [3], ,,,, [360]
    from cte
    pivot (SUM(PeriodData)
    FOR PeriodNumber IN (
    [0], [1], [2], [3], ..., [360]
    ) as pvt;
    SELECT * from PivotTable;
    SELECT
    DateKey ,
    VersionNumber ,
    SetID ,
    ClassID ,
    VariableName ,
    PeriodNumber ,
    PeriodData
    from StagingTable;
    The first query (pivot query) had a cost of 41%, the second 25% (select pivottable) and the third 34% (select base table).  These are nowhere close to the ratios of the amount of time that it takes to run these queries (pivot query 3.5 minutes,
    select  PivotTable 5 seconds and select base table almost one minute).
    For the following:
    WITH cte as (
    SELECT
    DateKey ,
    VersionNumber ,
    SetID ,
    ClassID ,
    VariableName ,
    PeriodNumber ,
    PeriodData
    from StagingTable
    SELECT
    DateKey ,
    VersionNumber ,
    SetID ,
    ClassID ,
    VariableName,
    [0], [1], [2], [3], ,,,, [360]
    into newTable1
    from cte
    pivot (SUM(PeriodData)
    FOR PeriodNumber IN (
    [0], [1], [2], [3], ..., [360]
    ) as pvt;
    SELECT *
    into newTable2
    from PivotTable;
    SELECT
    DateKey ,
    VersionNumber ,
    SetID ,
    ClassID ,
    VariableName ,
    PeriodNumber ,
    PeriodData
    into newTable3
    from StagingTable;
    The distribution of query cost is strikingly different.  The pivot query has a cost of 98% and the other two queries have costs of 1%.  The big difference between these queries and the versions that just output the results (in the execution plan)
    is in the table insert.  The pivot query shows a cost of 26,000 while the select from pivottable shows cost of 160 and select from StagingTable shows cost of 280.
    What else can I look at?  Also, what else can I try to optimize the pivot query.
    For now, I am going to see if I get better performance letting SSRS do the pivoting.
    Russel Loski, MCT, MCSE Data Platform/Business Intelligence. Twitter: @sqlmovers; blog: www.sqlmovers.com

    I have finally nailed down what is causing the bottleneck.
    The Compute Scalar step for some reason shows almost no cost to the execution plan.  But I noticed that the actual number of rows is 5 million (the same as the scan).  It appears that SQL Server expands every row to 360+ columns, all 5 million
    of them.
    So I did an experiment.  I took the table that I was populating and did a cross join to a number table.  This table has 30 K rows and 360 columns.  I figured that if I select 150 rows from the number table it will generate around 5 million
    rows.  The results were almost identical to using the MAX(CASE WHEN ...) construct:  1 minute and some change.
    I then cross joined with only 75 rows.  It took 30 seconds.  37 rows took about 15 seconds.
    So the Compute Scalar costs a lot more then the Execution plan analyzer says.
    SSIS appears to gather one row at a time.  Once it finishes one row, one group by set, it sends the row on its way.  So, in my case, the 5 million rows is read in with 7 columns and 30 K rows are output with 365 columns or so.
    SQL Server creates 5 million rows with 365 columns, then aggregates them down to 30 K rows.
    Thank you, Tom for you discussion with me on this.  I think that I can present my thoughts to my lead.
    Russel Loski, MCT, MCSE Data Platform/Business Intelligence. Twitter: @sqlmovers; blog: www.sqlmovers.com

  • Possible Bug? SQL query changing the Cursor Type from Scrollable to non Scrollable in a ResultSet

    Hi all,
    I've been beating my head against this for a few days now, and while
    there is a workaround, I haven't found out what's causing this to
    happen.
    Every other SQL query except for this one particular query works fine
    and returns a scrollable result set. That one query on the other hand,
    returns a non-scrollable result set.
    Here's the code which is calling the query:
    sqlStatement = getSQLFromFile();
    debug("SQL statment = " + sqlStatement);
    stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
    debug(sqlStatement);
    rst = stmt.executeQuery(sqlStatement);
    debug("The type is " + rst.getType());
    rst.last();
    For most queries, the output is "The type is 1004" - which means the
    resultset is scrollable - as it should be.
    For one particular query, the output is "The type is 1003" which means
    that the result set is of type forward-only.
    Of course, calling rst.last() fails in the second case.
    If the difference between the queries was drastic, I might have
    something to go on. I've tested this out with different size queries,
    but the switch between having the type incorrectly changed is the
    deletion of a 0x0a 0x0d on the first line.
    I.E. this means the failing query reads :
    "select
    from........."
    and the query which works reads
    "select *
    from........."
    I've looked at the failing query in it's binary format, and that's the
    only difference I can discern.
    To further confuse things, there are other queries which have a
    similar format - and which work.
    I've read about a bug in Weblogic 5.1 SP9 which ignores the setting of
    the Statement to return a ResultSet with a scrollable cursor, and
    while this seems to be a bug, it doesn't seem the same bug at all -
    besides, I'm using Weblogic 6.0 with SP1 on a W2K system.
    Does anyone have any ideas as to what might be causing this? I'm
    stumped..

    Ryan D'Silva wrote:
    Hi Joe,
    I'm using the Oracle thin driver -
    oracle.jdbc.driver.OracleDriver - version #8.1.6.0.0
    and the DBMS is
    "Oracle9i Enterprise Edition Release 9.2.0.2.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.2.0 - Production"
    Does that help?Yes. Two things: TYou should probably upgrade the oracle thin
    driver, by downloading the latest appropriate one from their site,
    and make sure it's ahead of all weblogic jars in the classpath the
    server builds for itself. Also, let's see how simple we can make the
    problem. Would you please repeat the JDBC that demonstrated the problem,
    in a small standalone java program that uses a direct thin driver connection,
    getting weblogic out of the picture? (The problem does sound like
    and oracle driver issue).
    Joe
    >
    >
    Thanks,
    - ryan
    You don't say what DBMS and what JDBC driver you're using for the pool.
    That is likely to be the issue. Let me know.
    Joe
    Here's the code which is calling the query:
    sqlStatement = getSQLFromFile();
    debug("SQL statment = " + sqlStatement);
    stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
    debug(sqlStatement);
    rst = stmt.executeQuery(sqlStatement);
    debug("The type is " + rst.getType());
    rst.last();
    For most queries, the output is "The type is 1004" - which means the
    resultset is scrollable - as it should be.
    For one particular query, the output is "The type is 1003" which means
    that the result set is of type forward-only.
    Of course, calling rst.last() fails in the second case.
    If the difference between the queries was drastic, I might have
    something to go on. I've tested this out with different size queries,
    but the switch between having the type incorrectly changed is the
    deletion of a 0x0a 0x0d on the first line.
    I.E. this means the failing query reads :
    "select
    from........."
    and the query which works reads
    "select *
    from........."
    I've looked at the failing query in it's binary format, and that's the
    only difference I can discern.
    To further confuse things, there are other queries which have a
    similar format - and which work.
    I've read about a bug in Weblogic 5.1 SP9 which ignores the setting of
    the Statement to return a ResultSet with a scrollable cursor, and
    while this seems to be a bug, it doesn't seem the same bug at all -
    besides, I'm using Weblogic 6.0 with SP1 on a W2K system.
    Does anyone have any ideas as to what might be causing this? I'm
    stumped..

Maybe you are looking for