Help with nested select query

Here is my code , i dont have any experience with writing the nested sql , i got the below code , which needs to be modified adding a case statement which will show util_rate for 2 conditions
1. given in where condition ( to_char(time_stamp,'HH24') >= '09' and to_char(time_stamp,'HH24') <= '19')
2.Apposite to the condition above (to_char(time_stamp,'HH24') < '09'and to_char(time_stamp,'HH24') > '19')
could anybody please help me in adding the 2nd condition to the below query , please share any documentation you have for learning how to write nested sql,
Thank you
select device,time_stamp,
sum(ActiveHRS)/sum(AvailHRS) as RATE
from
select device,time_stamp,
case when usage >0 then 1
else 0 end as ActiveHRS,
'1' as AvailHRS
from
select device,time_stamp,
sum(case
when state = 9 then 0
when state = 0 then 0
else 1 end) as usage
from A
where to_char(time_stamp,'HH24') >= '09'
and to_char(time_stamp,'HH24') <= '19'
and to_char(time_stamp, 'D') in (2,3,4,5,6)
group by device, time_stamp
group by device,time_stamp

Here is the DDL :
desc rumi_all
Name     Null   Type    
RUMI_DEVICE      VARCHAR2(20)
STATE         NUMBER(38) 
TIME_STAMP      DATE     
LOCATION       VARCHAR2(50) Here is some sample data :
RUMI_DEVICE   STATE   TIME_STAMP    LOCATION
10.45.28.86     0     15-JUN-10      WA-102
10.45.28.51     0     15-JUN-10      WA-102
10.45.28.63     0     15-JUN-10      WA-102
10.45.29.47     9     15-JUN-10      WA-120I used the below query to get the util for the hours 9am - 7pm
select rumi_device,time_stamp,
sum(ActiveHRS)/sum(AvailHRS) as RATE
from
select rumi_device,time_stamp,
case when usage >0 then 1
else 0 end as ActiveHRS,
'1' as AvailHRS
from
select rumi_device,time_stamp,
sum(case
when state = 9 then 0
when state = 0 then 0
else 1 end) as usage
from rumi_all
where to_char(time_stamp,'HH24') >= '09'
and to_char(time_stamp,'HH24') <= '19'
and to_char(time_stamp, 'D') in (2,3,4,5,6)
group by rumi_device, time_stamp
group by rumi_device,time_stamp
Acquired Out for the above query :
RUMI_DEVICE      TIME_STAMP     UTIL_RATE
10.45.29.47     15-JUN-10       0.234
10.45.28.63     15-JUN-10             0.123
10.45.29.47     15-JUN-10             0.987
10.45.29.47     16-JUN-10             0.23Desired output :I want 2 extra columns which shows util rate for the above condition i.e 9am - 7pm(core hours) and also opposite to that condition after 7pm - before 9am(say, non core hours)
Desired out put :
RUMI_DEVICE TIME_STAMP  Core_Util_Rate   Non_Core_UtilRate
10.45.29.4    15-JUN-10       0.234              0.003
10.45.28.63   15-JUN-10     0.123              0.001
10.45.29.47   15-JUN-10              0.987              0.023
10.45.29.47   16-JUN-10              0.23                  0Hope this helps in answering my question , and also could you please share some document to learn writing nested sql's , i always had tough time in understanding this :-(

Similar Messages

  • Need some help with the Select query.

    Need some help with the Select query.
    I had created a Z table with the following fields :
    ZADS :
    MANDT
    VKORG
    ABGRU.
    I had written a select query as below :
    select single vkorg abgru from ZADS into it_rej.
    IT_REJ is a Work area:
    DATA : BEGIN OF IT_REJ,
            VKORG TYPE VBAK-VKORG,
            ABGRU TYPE VBAP-ABGRU,
           END OF IT_REJ.
    This is causing performance issue. They are asking me to include the where condition for this select query.
    What should be my select query here?
    Please suggest....
    Any suggestion will be apprecaiated!
    Regards,
    Developer

    Hello Everybody!
    Thank you for all your response!
    I had changes this work area into Internal table and changed the select query. PLease let me know if this causes any performance issues?
    I had created a Z table with the following fields :
    ZADS :
    MANDT
    VKORG
    ABGRU.
    I had written a select query as below :
    I had removed the select single and insted of using the Structure it_rej, I had changed it into Internal table 
    select vkorg abgru from ZADS into it_rej.
    Earlier :
    IT_REJ is a Work area:
    DATA : BEGIN OF IT_REJ,
    VKORG TYPE VBAK-VKORG,
    ABGRU TYPE VBAP-ABGRU,
    END OF IT_REJ.
    Now :
    DATA : BEGIN OF IT_REJ occurs 0,
    VKORG TYPE VBAK-VKORG,
    ABGRU TYPE VBAP-ABGRU,
    END OF IT_REJ.
    I guess this will fix the issue correct?
    PLease suggest!
    Regards,
    Developer.

  • I need help with a SELECT query - help!

    Hello, I need help with a select statement.
    I have a table with 2 fields as shown below
    Name | Type
    John | 1
    John | 2
    John | 3
    Paul | 1
    Paul | 2
    Paul | 3
    Mark | 1
    Mark | 2
    I need a query that returns everything where the name has type 1 or 2 but not type 3. So in the example above the qery should bring back all the "Mark" records.
    Thanks,
    Ian

    Or, if the types are sequential from 1 upwards you could simply do:-
    SQL> create table t as
      2  select 'John' as name, 1 as type from dual union
      3  select 'John',2 from dual union
      4  select 'John',3 from dual union
      5  select 'Paul',1 from dual union
      6  select 'Paul',2 from dual union
      7  select 'Paul',3 from dual union
      8  select 'Paul',4 from dual union
      9  select 'Mark',1 from dual union
    10  select 'Mark',2 from dual;
    Table created.
    SQL> select name
      2  from t
      3  group by name
      4  having count(*) <= 2;
    NAME
    Mark
    SQL>Or another alternative if they aren't sequential:
    SQL> ed
    Wrote file afiedt.buf
      1  select name from (
      2    select name, max(type) t
      3    from t
      4    group by name
      5    )
      6* where t < 3
    SQL> /
    NAME
    Mark
    SQL>Message was edited by:
    blushadow

  • Help with nestes sql query

    Hi,
    I am trying to do the following:
    SELECT b_cost-(stay_cost+p_sal+bc_sal+cs_sal+ms_sal)
         FROM
              (SELECT sum(b_cost) b_cost FROM b)
              (SELECT sum(cost) stay_cost FROM sl)
              (SELECT sum(sal) p_sal FROM p)
              (SELECT sum(sal) bc_sal FROM bc)
              (SELECT sum(sal) cs_sal FROM cs)
              (SELECT sum(sal) ms_sal FROM ms)
         );I cannot execute the query ...
    What am I doing wrong?
    thanks

    Did you try my code.. ?????
    it's work fine for me..
    with b
    as
    (select 1 b_cost from dual),
    sl as
    (select 1 cost from dual),
    p as
    (select 1 sal from dual),
    bc as
    (select 1 sal from dual),
    cs as
    (select 1 sal from dual),
    ms as
    (select 1 sal from dual)
    SELECT tb.b_cost-(ts1.stay_cost+tp.p_sal+tbc.bc_sal+tcs.cs_sal+tms.ms_sal)
    FROM
              (SELECT sum(b_cost) b_cost FROM b) tb,
              (SELECT sum(cost) stay_cost FROM sl) ts1,
              (SELECT sum(sal) p_sal FROM p) tp,
              (SELECT sum(sal) bc_sal FROM bc) tbc,
              (SELECT sum(sal) cs_sal FROM cs) tcs,
              (SELECT sum(sal) ms_sal FROM ms) tms
    TB.B_COST-(TS1.STAY_COST+TP.P_SAL+TBC.BC_SAL+TCS.CS_SAL+TMS.MS_SAL)
                                                                     -4
    1 row selected.aweiden option works too.. !!
    what oracle version do you have ????
    Edited by: dask99 on Oct 30, 2008 3:40 PM

  • Help with a select query

    Hi Guys,
    For example I have 2 tables:
    I wish to list out the owner, table_name, total count of chain row of the table, num rows by joining the below 2 tables.
    Can advise how can i do it?
    Currently i'm doing it by executing this statement but very slow:
    select a.owner_name, a.table_name, count(*), b.num_Rows
    from system.chained_rows a, dba_tables b
    where a.owner_name=b.owner
    and a.table_name=b.table_name
    and b.num_Rows>0
    group by a.owner_name, a.table_name, b.num_Rows
    having count(*)*100/b.num_Rows>10;
    TABLE INFORMATION:
    1. CHAINED_ROWS (one table name can have multiple chain row id records)
    column:
    1. owner
    2. table_name
    3. chain row id
    2. DBA_TABLES (one table name only one record)
    column:
    1. owner
    2. table_name
    3. num_rows
    thanks

    Hi,
    I think u mis-inteprete my question.
    My question is more on how to formulate a sql to get the output i hope so.. and not how to get chain counts.
    I wish to list out the owner, table_name, total count of chain row of the table, num rows by joining the below 2 tables.
    Can advise how can i do it?
    Currently i'm doing it by executing this statement but very slow:
    select a.owner_name, a.table_name, count(*), b.num_Rows
    from system.chained_rows a, dba_tables b
    where a.owner_name=b.owner
    and a.table_name=b.table_name
    and b.num_Rows>0
    group by a.owner_name, a.table_name, b.num_Rows
    having count(*)*100/b.num_Rows>10;
    TABLE INFORMATION:
    1. CHAINED_ROWS (one table name can have multiple chain row id records)
    column:
    1. owner
    2. table_name
    3. chain row id
    2. DBA_TABLES (one table name only one record)
    column:
    1. owner
    2. table_name
    3. num_rows
    thanks

  • Performance issue after Upgrade from 4.7 to ECC 6.0 with a select query

    Hi All,
    There is a Performance issue after Upgrade from 4.7 to ECC 6.0 with a select query in a report painter.
    This query is working fine when executed in 4.7 system where as it is running for more time in ECC6.0.
    Select query is on the table COSP.
    SELECT (FIELD_LIST)
            INTO CORRESPONDING FIELDS OF TABLE I_COSP PACKAGE SIZE 1000
            FROM  COSP CLIENT SPECIFIED
            WHERE GJAHR IN SELR_GJAHR
              AND KSTAR IN SELR_KSTAR
              AND LEDNR EQ '00'
              AND OBJNR IN SELR_OBJNR
              AND PERBL IN SELR_PERBL
              AND VERSN IN SELR_VERSN
              AND WRTTP IN SELR_WRTTP
              AND MANDT IN MANDTTAB
            GROUP BY (GROUP_LIST).
       LOOP AT I_COSP      .
         COSP                           = I_COSP      .
         PERFORM PCOSP       USING I_COSP-_COUNTER.
         CLEAR: $RWTAB, COSP                          .
         CLEAR CCR1S                         .
       ENDLOOP.
    ENDSELECT.
    I have checked with the table indexes, they were same as in 4.7 system.
    What can be the reson for the difference in execution time. How can this be reduced without adjusting the select query.
    Thanks in advance for the responses.
    Regards,
    Dedeepya.

    Hi,
    ohhhhh....... lots of problems in select query......this is not the way you should write it.
    Some generic comments:
    1. never use SELECT
                       endselect.
       SELECT
      into table
       for all entries in table
      where.
       use perform statment after this selection.
    2. Do not use into corresponding fields. use exact structure type.
    3. use proper sequence of fields in the where condition so that it helps table go according to indexes.
        e.g in your case
              sequence should be
    LEDNR
    OBJNR
    GJAHR
    WRTTP
    VERSN
    KSTAR
    HRKFT
    VRGNG
    VBUND
    PARGB
    BEKNZ
    TWAER
    PERBL
    sequence should be same as defined in table.
    Always keep select query as simple as possible and perform all other calculations etc. afterwords.
    I hope it helps.
    Regards,
    Pranaya

  • Help with an SQL Query on the Logger

    We are running UCCE 8.5(3) and need help with an SQL query. When I run the below I would also like to see skill group information(name preferably)? Any help would be greatly appreciated!
    select * from dbo.t_Termination_Call_Detail where DateTime between '10-11-2012 00:00:00:00' and
    '10-11-2012 23:59:59:59'

    David, thanks for replying.  Unfortunitly I don't know enough about SQL to put that into a query and have it return data.  Would you be able to give an example on what the query would look like?

  • What is the wrong with my select query

    HI All,
    TYPES: BEGIN OF t_equi,
             equnr          TYPE equi-equnr,
             aedat          TYPE equi-aedat,
             matnr          TYPE equi-matnr,
             sernr          TYPE equi-sernr,
             kunde          TYPE equi-kunde,
             zzreg_date     TYPE equi-zzreg_date,
             zzin_indic     TYPE equi-zzin_indic,
             zzinvoice_num  TYPE equi-zzinvoice_num,
             zzinvoice_date TYPE equi-zzinvoice_date,
             kund1          TYPE equz-kund1,
          END OF t_equi,
    DATA: it_equi        TYPE TABLE OF t_equi,
      SELECT equnr
             aedat
             matnr
             sernr
             kunde          "Ship to
             zzreg_date
             zzin_indic
             zzinvoice_num
             zzinvoice_date
             kund1            "Sold to
             INTO TABLE it_equi
             FROM equi AS a
             INNER JOIN equz AS b
             ON a~equnr = b~equnr
             WHERE a~equnr      IN s_equnr AND
    *               aedat GE gv_rdate AND
                   a~matnr      IN s_matnr AND
                   a~sernr      IN s_sernr AND
                   a~kunde      IN r_shpbr_kunde AND
                   a~zzin_indic IN s_indic  AND
                   b~datbi      EQ c_datbi  AND 
                   b~kund1     IN r_sldbr_kund1 .
    what is the wrong with this select query.. ?
    its giving me error  "The column name "EQUNR" is unclear ."
    Thanks

    Hi ,
    write  tablename or alias in select also
    SELECT a~equnr and check.
    Regards

  • Help regarding a select Query

    hi All,
    I have one requirement.I wonder whether i can do it in a single SQL Statement or not.
    I have tab1 with columns c1,c2,c3,c4,....,Logon_time
    I have tab2 with columns C1,c2,c3,c4.....,Logoff_time
    All the columns are same for two tables except that logon_time and logoff_time as mentioned above.
    tab1 will have all the information of user who logon to database.
    tab2 will have all the information of user who logoff from DB.
    Now i i have to generate a report which shows all the user info and logon Duration.For that i can use logoff_time - logon_time.but the challenge here is logoff_time dont contain rows for the users who logon to database byt yet to logoff.
    So for them logoff_time-logon_time showing -ve Duration.
    So I want Duration as logoff_time-logon_time for all the rows.But for those users who yet to logoff i want duration as "YET to Logoff"
    Is this possible with single Select Query.
    Thanks
    Pramod

    Hi, Pramod,
    You need to join tab_1 to tab_2. Since not every row in tab_1 will have a matching row in tab_2, make it an outer join.
    How do you know which row in tab_1 matches which row in tab_2?
    I assume there's some column (let's say c1) that identifies a user. A user can have several sessions going at the same time, however.
    The following query matches the n-th logon_time in tab_1 with the n-th logoff_time in tab_2 for the same user:
    WITH     numbered_tab_1     AS
         SELECT  c1, c2, c3, c4, ..., logon_time
         ,     ROW_NUMBER () OVER ( PARTITION BY  c1     -- or whatever identifies user
                                   ORDER BY          logon_time
                           ) AS r_num
         FROM     tab_1
    ,     numbered_tab_2     AS
         SELECT  c1, c2, c3, c4, ..., logon_time
         ,     ROW_NUMBER () OVER ( PARTITION BY  c1     -- or whatever identifies user
                                   ORDER BY          logoff_time
                           ) AS r_num
         FROM     tab_2
    SELECT     t1.c1, t1.c2, t1.c3, t1.c4, ..., t1.logon_time     -- or whatever you want
    ,     t2.c1, t2.c2, t2.c3, t2.c4, ..., t2.logoff_time
    ,     NVL ( TO_CHAR (24 * (t2.logff_time - t1.logon_time))    -- duration in hours
             , 'Yet to Logoff'
             )         AS duration
    FROM             numbered_tab_1     t1
    LEFT OUTER JOIN     numbered_tab_2     t2     ON   t1.c1     = t2.c1
                                     AND  t1.r_num  = t2.r_num
    ;I can test this if you'll post some sample data and the results you want from that data.
    The query above matches logons and logoffs only by user and time
    For example, say I log on at 10:00.
    At 10:45, I open another window and log on again, but log off at 10:50 after 5 minutes.
    At 11:30 I log off the first session.
    If you were interested in sessions that lasted over 1 hour, the query above would not be accurate. It would show one session starting at 10:00 and ending at 10:50, and another session starting at 10:45 and ending at 11:30. To know that the first session to end was the second sessiion in order of beginning, you would have to have another column, say a unique session id.
    If you're only interested in the number of sessions, or the total time connected per user, then the query above will be good enough.
    Edited by: Frank Kulash on Jul 6, 2009 12:07 PM

  • Selection screen - search help with dynamic sql query

    hey ,
    is it possible to change the search help of the selection field ?
    when i create the range table i put a data element :
    create a range table that consists of this new data element
      LT_RANGE_TABLE = WD_THIS->M_HANDLER->CREATE_RANGE_TABLE( I_TYPENAME = 'S_CARR_ID' ).
    can i control the search help via the the data element or by other methods ?
    i want that when the user press F4 the values that will show is the result of a sql query that i will write .
    is it possible ?
    thanks
    ASA.

    Hi,
    yes it is possible...
    This is my test code for say personal number select options...
    lt_range_table = wd_this->m_handler->create_range_table(
      i_typename = 'PERSNO' ).
    add a new field to the selection
      wd_this->m_handler->add_selection_field(
      i_id = 'PERSNO'
    I_VALUE_HELP_TYPE = if_wd_value_help_handler=>CO_PREFIX_SEARCHHELP
    I_VALUE_HELP_ID = 'ZHELP_WDA_PERNR'   "this is the custom search help we need to create
    I_NO_INTERVALS = abap_true
      it_result = lt_range_table
      i_read_only = read_only ).
    do the following:
    1) copy the std function module: F4IF_SHLP_EXIT....to ZF4IF_SHLP_EXIT_pernr (in my case i am testing for pernr so my fm
    name is like that....obviously it can be anything you want...under the recommended naming convention)
    2) look for "STEP SELECT"
    STEP SELECT    (Select values)
    3)write the code as follows:
    "NOTE: this is my testing code...but you can build your logic on it....
    IF CALLCONTROL-STEP = 'SELECT'.
    types: begin of zpri_listing,
    pernr type PERSNO,
    end of zfund_listing.
    DATA: lo_syuname TYPE sy-uname.
    data itab type standard table of Zpri_LISTING.
    data wa type zpri_listing.
        DATA : t_fields LIKE TABLE OF shlp_tab-fielddescr.
        DATA : w_fields LIKE LINE OF shlp_tab-fielddescr.
        DATA : l_fname TYPE dfies-lfieldname.
        IF lo_syuname <> sy-uname.  "means we were here before and ITAB is filled...fm retains its data values...unless refresh happens
    "this if condition make sure that we do not do this select all the time as long as the same user is logged in...
    "a user can press f4 many times...you might want to enhance this logic a little bit more for performance
          lo_syuname = sy-uname.
    ))))))))))))))HERE DO YOUR SELECT(((((((((((((((((((((
    select pernr from "sometable" into table itab.
        ENDIF.
        LOOP AT shlp_tab.
          LOOP AT shlp_tab-fielddescr INTO w_fields.
            l_fname = w_fields-fieldname.
            CALL FUNCTION 'F4UT_PARAMETER_RESULTS_PUT'
              EXPORTING
                parameter               = w_fields-fieldname
              OFF_SOURCE              = 0
              LEN_SOURCE              = 0
              VALUE                   =
               fieldname               = l_fname
              TABLES
                shlp_tab                = shlp_tab
                record_tab              = record_tab
                source_tab              =  itab
              CHANGING
                shlp                    = shlp
                callcontrol             = callcontrol
             EXCEPTIONS
               parameter_unknown       = 1
               OTHERS                  = 2
          ENDLOOP.
        ENDLOOP.
        IF sy-subrc EQ 0.
          callcontrol-step = 'DISP'.
        ELSE.
          callcontrol-step = 'EXIT'.
        ENDIF.
        EXIT. "Don't process STEP DISP additionally in this call.
      ENDIF.
    4) save and activate this function module...
    5) go to se11 and create "Elementary srch hlp"....
    6) fill out all the necessary fields...i am assuming that you already know how to create the search helps...
    look for this field: "Search help exit" and put your function name which you created in the above steps...
    in this example i have: ZF4IF_SHLP_EXIT_pernr....
    7) create and activate the search help....
    hope this helps...i just tested this and it is working for me....
    Thanks..
    AS...

  • Help with the problem query

    Hi,
    I have another query running slow when executed from cognos. It is also not returning any output continues to execute,
    with "Union15" as (
    select distinct CASE WHEN(substr(to_char(FLOOR("EES_ENERGY_MASTER"."DISC_MON"/100)), 1, 4) IS NULL) OR (case substr(to_char(FLOOR("EES_ENERGY_MASTER"."DISC_MON"/100)), 5, 1) when '1' then 'Q1' when '2' then 'Q2' when '3' then 'Q3' when '4' then 'Q4' end  IS NULL) THEN NULL ELSE (substr(to_char(FLOOR("EES_ENERGY_MASTER"."DISC_MON"/100)), 1, 4)||case substr(to_char(FLOOR("EES_ENERGY_MASTER"."DISC_MON"/100)), 5, 1) when '1' then 'Q1' when '2' then 'Q2' when '3' then 'Q3' when '4' then 'Q4' end ) END "QUARTER", "EES_ENERGY_MASTER"."PAT_KEY" "Cases_Using_Energy", 0 "Total_Cases"
    from "MDM_DBA"."EES_ENERGY_MASTER" "EES_ENERGY_MASTER", "MDM_DBA"."EES_CONS_PROV" "EES_CONS_PROV"
    where "EES_ENERGY_MASTER"."DISC_MON">=2006101 and "EES_ENERGY_MASTER"."PDCT_CAT"='Energy' and substr("EES_ENERGY_MASTER"."ICD_CODE", 1, 2)='68-gyn' and "EES_ENERGY_MASTER"."MANUFACTURER"='EES' and "EES_CONS_PROV"."CONS_06_09_YN" in ('N', 'Y') and "EES_ENERGY_MASTER"."PROV_ID"="EES_CONS_PROV"."PROV_ID" union 
    select CASE WHEN(substr(to_char(FLOOR("MVW_EES_ICD_STATS"."DISC_QTR")), 1, 4) IS NULL) OR (case substr(to_char(FLOOR("MVW_EES_ICD_STATS"."DISC_QTR")), 5, 1) when '1' then 'Q1' when '2' then 'Q2' when '3' then 'Q3' when '4' then 'Q4' end  IS NULL) THEN NULL ELSE (substr(to_char(FLOOR("MVW_EES_ICD_STATS"."DISC_QTR")), 1, 4)||case substr(to_char(FLOOR("MVW_EES_ICD_STATS"."DISC_QTR")), 5, 1) when '1' then 'Q1' when '2' then 'Q2' when '3' then 'Q3' when '4' then 'Q4' end ) END "QUARTER", 0 "Cases_Using_Energy", count("MVW_EES_ICD_STATS"."CASES") "Total_Cases"
    from "MDM_DBA"."MVW_EES_ICD_STATS" "MVW_EES_ICD_STATS", "MDM_DBA"."EES_CONS_PROV" "EES_CONS_PROV", "MDM_DBA"."EES_HOSP_CHG_PROV" "EES_HOSP_CHG_PROV"
    where "MVW_EES_ICD_STATS"."DISC_QTR">=20061 and "MVW_EES_ICD_STATS"."ICD_GROUP"='68-gyn' and "EES_CONS_PROV"."CONS_06_09_YN" in ('N', 'Y') and "EES_HOSP_CHG_PROV"."PDCT_CAT"='Energy' and "EES_HOSP_CHG_PROV"."MANUFACTURER"='EES' and "MVW_EES_ICD_STATS"."PROV_ID"="EES_CONS_PROV"."PROV_ID" and "MVW_EES_ICD_STATS"."PROV_ID"="EES_HOSP_CHG_PROV"."PROV_ID"
    group by CASE WHEN(substr(to_char(FLOOR("MVW_EES_ICD_STATS"."DISC_QTR")), 1, 4) IS NULL) OR (case substr(to_char(FLOOR("MVW_EES_ICD_STATS"."DISC_QTR")), 5, 1) when '1' then 'Q1' when '2' then 'Q2' when '3' then 'Q3' when '4' then 'Q4' end  IS NULL) THEN NULL ELSE (substr(to_char(FLOOR("MVW_EES_ICD_STATS"."DISC_QTR")), 1, 4)||case substr(to_char(FLOOR("MVW_EES_ICD_STATS"."DISC_QTR")), 5, 1) when '1' then 'Q1' when '2' then 'Q2' when '3' then 'Q3' when '4' then 'Q4' end ) END)
    select "T1"."C0" "levelkey", "T1"."C1" "Cases_Using_Energy", "T0"."C0" "Cases_Using_Energy1", "T1"."C2" "Total_Cases"
    from (
    select count(distinct "Union15"."Cases_Using_Energy") "C0"
    from "Union15") "T0", (
    select "Union15"."QUARTER" "C0", count(distinct "Union15"."Cases_Using_Energy") "C1", sum("Union15"."Total_Cases") "C2"
    from "Union15"
    group by "Union15"."QUARTER") "T1"The explain plan is as follows,
    PLAN_TABLE_OUTPUT
    | Id  | Operation                             |  Name                        | Rows  | Bytes |TempSpc| Cost  |
    |   0 | SELECT STATEMENT                      |                              |     1 |    50 |       |    22 |
    |   2 |  TEMP TABLE TRANSFORMATION            |                              |       |       |       |       |
    |   1 |   RECURSIVE EXECUTION                 | SYS_LE_2_0                   |       |       |       |       |
    |   0 |    INSERT STATEMENT                   |                              |  3053 |   128K|       |  1372 |
    |   1 |     LOAD AS SELECT                    |                              |       |       |       |       |
    |   2 |      SORT UNIQUE                      |                              |  3053 |   128K|   376K|  1372 |
    |   3 |       UNION-ALL                       |                              |       |       |       |       |
    |*  4 |        HASH JOIN                      |                              |  3052 |   128K|       |   185 |
    |*  5 |         TABLE ACCESS FULL             | EES_CONS_PROV                |   622 |  3732 |       |     2 |
    |*  6 |         TABLE ACCESS BY INDEX ROWID   | EES_ENERGY_MASTER            |  3055 |   110K|       |   182 |
    |*  7 |          INDEX RANGE SCAN             | IDX_ENERGY_PDCT_CAT          |  1978 |       |       |  2478 |
    |   8 |        SORT GROUP BY                  |                              |     1 |    40 |       |  1160 |
    |*  9 |         TABLE ACCESS BY INDEX ROWID   | EES_HOSP_CHG_PROV            |     4 |    72 |       |     1 |
    |  10 |          NESTED LOOPS                 |                              |     1 |    40 |       |  1157 |
    |  11 |           NESTED LOOPS                |                              |     1 |    22 |       |  1156 |
    |* 12 |            TABLE ACCESS BY INDEX ROWID| MVW_EES_ICD_STATS            |     1 |    16 |       |  1155 |
    |* 13 |             INDEX RANGE SCAN          | MVWICDSTATS_DISCQTR_IDX      |    13M|       |       | 26068 |
    |* 14 |            TABLE ACCESS BY INDEX ROWID| EES_CONS_PROV                |     1 |     6 |       |     1 |
    |* 15 |             INDEX UNIQUE SCAN         | EES_CONS_PROV_PK             |     1 |       |       |       |
    |* 16 |           INDEX RANGE SCAN            | PROV_ID_IDX_2                |    65 |       |       |     1 |
    |   3 |   MERGE JOIN CARTESIAN                |                              |     1 |    50 |       |    22 |
    |   4 |    VIEW                               |                              |     1 |    13 |       |     3 |
    |   5 |     SORT GROUP BY                     |                              |     1 |    13 |       |       |
    |   6 |      VIEW                             |                              |  3053 | 39689 |       |     3 |
    |   7 |       TABLE ACCESS FULL               | SYS_TEMP_0FD9D68B3_C112F95D  |  3053 |   110K|       |     3 |
    |   8 |    VIEW                               |                              |     1 |    37 |       |    19 |
    |   9 |     SORT GROUP BY                     |                              |     1 |    37 |       |    19 |
    |  10 |      VIEW                             |                              |  3053 |   110K|       |     3 |
    |  11 |       TABLE ACCESS FULL               | SYS_TEMP_0FD9D68B3_C112F95D  |  3053 |   110K|       |     3 |
    Predicate Information (identified by operation id):
       4 - access("EES_ENERGY_MASTER"."PROV_ID"="EES_CONS_PROV"."PROV_ID")
       5 - filter("EES_CONS_PROV"."CONS_06_09_YN"='N' OR "EES_CONS_PROV"."CONS_06_09_YN"='Y')
       6 - filter("EES_ENERGY_MASTER"."DISC_MON">=2006101 AND SUBSTR("EES_ENERGY_MASTER"."ICD_CODE",1,2)='68-gyn'
                  AND "EES_ENERGY_MASTER"."MANUFACTURER"='EES')
       7 - access("EES_ENERGY_MASTER"."PDCT_CAT"='Energy')
       9 - filter("EES_HOSP_CHG_PROV"."PDCT_CAT"='Energy' AND "EES_HOSP_CHG_PROV"."MANUFACTURER"='EES')
      12 - filter("MVW_EES_ICD_STATS"."ICD_GROUP"='68-gyn')
      13 - access("MVW_EES_ICD_STATS"."DISC_QTR">=20061 AND "MVW_EES_ICD_STATS"."DISC_QTR" IS NOT NULL)
      14 - filter("EES_CONS_PROV"."CONS_06_09_YN"='N' OR "EES_CONS_PROV"."CONS_06_09_YN"='Y')
      15 - access("MVW_EES_ICD_STATS"."PROV_ID"="EES_CONS_PROV"."PROV_ID")
      16 - access("MVW_EES_ICD_STATS"."PROV_ID"="EES_HOSP_CHG_PROV"."PROV_ID")
    Please help with some solution.

    OK: the third parameter of the SUBSTR function indicates the (maximum) length of the returnd string.
    Therefore SUBSTR("EES_ENERGY_MASTER"."ICD_CODE",1,2) could possibly be '68' , but never '68-gyn'.
    '68-gyn' is just 4 characters too long.
    Urs

  • How can i use index in select query.. facing problem with the select query.

    Hi Friends,
    I am facing a serious problem in one of the select query. It is taking a lot of time to fetch data in Production Scenario.
    Here is the query:
      SELECT * APPENDING CORRESPONDING FIELDS OF TABLE tbl_summary
        FROM ztftelat LEFT JOIN ztfzberep
         ON  ztfzberep~gjahr = st_input-gjahr
         AND ztfzberep~poper = st_input-poper
         AND ztfzberepcntr  = ztftelatrprctr
        WHERE rldnr  = c_telstra_accounting
          AND rrcty  = c_actual
          AND rvers  = c_ver_001
          AND rbukrs = st_input-bukrs
          AND racct  = st_input-saknr
          AND ryear  = st_input-gjahr
          And rzzlstar in r_lstar                            
          AND rpmax  = c_max_period.
    There are 5 indices present for Table ZTFTELAT.
    Indices of ZTFTELAT:
      Name   Description                                               
      0        Primary key( RCLNT,RLDNR,RRCTY,RVERS,RYEAR,ROBJNR,SOBJNR,RTCUR,RUNIT,DRCRK,RPMAX)                                          
      005    Profit (RCLNT,RPRCTR)
      1        Ledger, company code, account (RLDNR,RBUKRS, RACCT)                                
      2        Ledger, company code, cost center (RLDNR, RBUKRS,RCNTR)                           
      3        Account, cost center (RACCT,RCNTR)                                        
      4        RCLNT/RLDNR/RRCTY/RVERS/RYEAR/RZZAUFNR                        
      Z01    Activity Type, Account (RZZLSTAR,RACCT)                                        
      Z02    RYEAR-RBUKRS- RZZZBER-RLDNR       
    Can anyone help me out why it is taking so much time and how we can reduce it ? and also tell me if I want to use index number 1 then how can I use?
    Thanks in advance.

    Hi Shiva,
    I am using two more select queries with the same manner ....
    here are the other two select query :
    ***************1************************
    SELECT * APPENDING CORRESPONDING FIELDS OF TABLE tbl_summary
        FROM ztftelpt LEFT JOIN ztfzberep
         ON  ztfzberep~gjahr = st_input-gjahr
         AND ztfzberep~poper = st_input-poper
         AND ztfzberepcntr  = ztftelptrprctr
        WHERE rldnr  = c_telstra_projects
          AND rrcty  = c_actual
          AND rvers  = c_ver_001
          AND rbukrs = st_input-bukrs
          AND racct  = st_input-saknr
          AND ryear  = st_input-gjahr
          and rzzlstar in r_lstar             
          AND rpmax  = c_max_period.
    and the second one is
    *************************2************************
      SELECT * APPENDING CORRESPONDING FIELDS OF TABLE tbl_summary
        FROM ztftelnt LEFT JOIN ztfzberep
         ON  ztfzberep~gjahr = st_input-gjahr
         AND ztfzberep~poper = st_input-poper
         AND ztfzberepcntr  = ztftelntrprctr
        WHERE rldnr  = c_telstra_networks
          AND rrcty  = c_actual
          AND rvers  = c_ver_001
          AND rbukrs = st_input-bukrs
          AND racct  = st_input-saknr
          AND ryear  = st_input-gjahr
          and rzzlstar in r_lstar                              
          AND rpmax  = c_max_period.
    for both the above table program is taking very less time .... although both the table used in above queries have similar amount of data. And i can not remove the APPENDING CORRESPONDING. because i have to append the data after fetching from the tables.  if i will not use it will delete all the data fetched earlier.
    Thanks on advanced......
    Sourabh

  • Help in Join Select Query

    Hi, Please help on the Select Join query. I want to compare code_stat_system1/code_stat_system2 and code_date_system1 /code_date_system2 column from table #system1 and #system2 but there is 2 rule to get correct row from table #system1 and #system2.
    Rule 1: We need to get max(code_date_system1) record from #system1  for every code_system1 for compare.
    Rule 1: We need to get max(code_date_system2) record from #system2  BUT BEFORE THE RECORD OF 'DKNOW' OF code_stat_system2 for every code_system2 for compare.
    drop table #system1,#system2
    create table #system1
    (Code_system1 varchar(10),code_stat_system1 varchar(10),code_date_system1 datetime)
    Insert into #system1 values ('10','Dead','2013-01-01')
    Insert into #system1 values ('10','Dead','2013-12-30')
    Insert into #system1 values ('10','UnOpen','2014-10-01')
    Insert into #system1 values ('10','Open','2014-11-01')   --This record should max(code_stat_system1) for compare
    Insert into #system1 values ('20','Dead','2013-12-01')
    Insert into #system1 values ('20','Dead','2013-12-30')
    Insert into #system1 values ('20','Open','2014-08-01')
    Insert into #system1 values ('20','UnOpen','2014-09-01') --This record should max(code_stat_system1) for compare
    create table #system2
    (Code_system2 varchar(10),code_stat_system2 varchar(10),code_date_system2 datetime)
    Insert into #system2 values ('10','Dead','2013-01-01')
    Insert into #system2 values ('10','Dead','2013-12-30')
    Insert into #system2 values ('10','Open','2014-10-01')
    Insert into #system2 values ('10','UnOpen','2014-12-01') --This record should max(code_stat_system2) which is before 'DKNOW' for compare
    Insert into #system2 values ('10','DKNOW','2015-01-01')
    Insert into #system2 values ('10','DKNOW','2015-02-01')
    Insert into #system2 values ('20','Dead','2013-12-01')
    Insert into #system2 values ('20','Dead','2013-12-30')
    Insert into #system2 values ('20','Open','2014-08-01')
    Insert into #system2 values ('20','UnOpen','2014-09-01') --This record should max(code_stat_system2) which is before 'DKNOW' for compare
    Insert into #system2 values ('20','DKNOW','2015-01-01')
    Insert into #system2 values ('20','DKNOW','2015-02-01')
    --Desired Output
    Code_system1  code_stat_system1  code_date_system1  Code_system1   code_stat_system2  code_date_system1    Rrmk_code_stat         Rrmk_code_date
    10            Open           2014-11-01        10          UnOpen         
    2014-12-01         Codes not matching     Dates not matching
    20            UnOpen         2014-09-01        20          UnOpen         
    2014-09-01         Codes matching          Dates matching
    Thanks.

    drop table #system1,#system2
    create table #system1
    (Code_system1 varchar(10),code_stat_system1 varchar(10),code_date_system1 datetime)
    Insert into #system1 values ('10','Dead','2013-01-01')
    Insert into #system1 values ('10','Dead','2013-12-30')
    Insert into #system1 values ('10','UnOpen','2014-10-01')
    Insert into #system1 values ('10','Open','2014-11-01') --This record should max(code_stat_system1) for compare
    Insert into #system1 values ('20','Dead','2013-12-01')
    Insert into #system1 values ('20','Dead','2013-12-30')
    Insert into #system1 values ('20','Open','2014-08-01')
    Insert into #system1 values ('20','UnOpen','2014-09-01') --This record should max(code_stat_system1) for compare
    create table #system2
    (Code_system2 varchar(10),code_stat_system2 varchar(10),code_date_system2 datetime)
    Insert into #system2 values ('10','Dead','2013-01-01')
    Insert into #system2 values ('10','Dead','2013-12-30')
    Insert into #system2 values ('10','Open','2014-10-01')
    Insert into #system2 values ('10','UnOpen','2014-12-01') --This record should max(code_stat_system2) which is before 'DKNOW' for compare
    Insert into #system2 values ('10','DKNOW','2015-01-01')
    Insert into #system2 values ('10','DKNOW','2015-02-01')
    Insert into #system2 values ('20','Dead','2013-12-01')
    Insert into #system2 values ('20','Dead','2013-12-30')
    Insert into #system2 values ('20','Open','2014-08-01')
    Insert into #system2 values ('20','UnOpen','2014-09-01') --This record should max(code_stat_system2) which is before 'DKNOW' for compare
    Insert into #system2 values ('20','DKNOW','2015-01-01')
    Insert into #system2 values ('20','DKNOW','2015-02-01')
    ;with mycte1 as (select * ,row_number() Over (partition by Code_system1 Order by code_date_system1 Desc ) rn from #system1)
    ,mycte2 as (select *,row_number() Over (partition by Code_system2 Order by code_date_system2 Desc ) rn2 from #system2
    where code_stat_system2<>'DKNOW')
    Select m1.Code_system1, m1.code_stat_system1, m1.code_date_system1, Code_system2, code_stat_system2,code_date_system2 ,
    case When code_date_system1=code_date_system2 then 'Dates matching' else 'Dates not matching' End as checkDate,
    case When code_stat_system1=code_stat_system2 then 'Codes matching' else 'Codes not matching' End as checkStat
    from mycte1 m1 inner join mycte2 m2 on m1.Code_system1= m2.Code_system2 and m1.rn=m2.rn2
    Where m1.rn=1

  • Help with Inner Join query in SQL

    Hope someone can help with this, as this is quite an involved project for me, and I'm just about there with it.
    My table structure is :
    table_packages
    packageID
    package
    packageDetails
    etc
    table_destinations
    destinationID
    destination
    destinationDetails
    etc
    table_packagedestinations
    packageID
    destinationID
    ..so nothing that complicated.
    So the idea is that I can have a package details page which shows the details of the package, along any destinations linked to that package via the packagedestinations table.
    So this is the last part really - to get the page to display the destinations, but I'm missing something along the way....
    This is the PHP from the header, including my INNER JOIN query....
    PHP Code:
    <?php
    $ParampackageID_WADApackages = "-1";
    if (isset($_GET['packageID'])) {
      $ParampackageID_WADApackages = (get_magic_quotes_gpc()) ? $_GET['packageID'] : addslashes($_GET['packageID']);
    $ParamSessionpackageID_WADApackages = "-1";
    if (isset($_SESSION['WADA_Insert_packages'])) {
      $ParamSessionpackageID_WADApackages = (get_magic_quotes_gpc()) ? $_SESSION['WADA_Insert_packages'] : addslashes($_SESSION['WADA_Insert_packages']);
    $ParampackageID2_WADApackages = "-1";
    if (isset($_GET['packageID'])) {
      $ParampackageID2_WADApackages = (get_magic_quotes_gpc()) ? $_GET['packageID'] : addslashes($_GET['packageID']);
    mysql_select_db($database_connPackages, $connPackages);
    $query_WADApackages = sprintf("SELECT packageID, package, costperpax, duration, baselocation, category, dateadded, agerange, hotel, educational_tours, field_trips, corporate_outings, plant_visits, budget_package, rollingtours, teambuilding, description, offer FROM packages WHERE packageID = %s OR ( -1= %s AND packageID= %s)", GetSQLValueString($ParampackageID_WADApackages, "int"),GetSQLValueString($ParampackageID2_WADApackages, "int"),GetSQLValueString($ParamSessionpackageID_WADApackages, "int"));
    $WADApackages = mysql_query($query_WADApackages, $connPackages) or die(mysql_error());
    $row_WADApackages = mysql_fetch_assoc($WADApackages);
    $totalRows_WADApackages = mysql_num_rows($WADApackages);
    $colname_educationalDestinations = "1";
    if (isset($_GET['PackageID'])) {
      $colname_educationalDestinations = (get_magic_quotes_gpc()) ? packageID : addslashes(packageID);
    mysql_select_db($database_connPackages, $connPackages);
    $query_educationalDestinations = sprintf("SELECT * FROM destinations INNER JOIN (packages INNER JOIN packagedestinations ON packages.packageID = packagedestinations.packageID) ON destinations.destinationID = packagedestinations.destinationID WHERE packages.packageID = %s ORDER BY destination ASC", GetSQLValueString($colname_educationalDestinations, "int"));
    $educationalDestinations = mysql_query($query_educationalDestinations, $connPackages) or die(mysql_error());
    $row_educationalDestinations = mysql_fetch_assoc($educationalDestinations);
    $totalRows_educationalDestinations = mysql_num_rows($educationalDestinations);
    ?>
    And where I'm trying to display the destinations themselves, I have : 
    <table>
            <tr>
                     <td>Destinations :</td>
                </tr>
               <?php do { ?>
            <tr>
                 <td><?php echo $row_educationalDestinations['destination']; ?></td>
            </tr>
            <?php } while ($row_educationalDestinations = mysql_fetch_assoc($educationalDestinations)); ?>
    </table>
    If anyone could have a quick look and help me out that would be much appreciated - not sure if its my SQL at the top, or the PHP in the page, but either way it would be good to get it working. 
    Thanks.

    First off, you need to get the database tables so that there is a relationship between them.
    In fact, if there is a one to one relationship, then it may be better to store all of your information in one table such as
    table_packages
    packageID
    package
    packageDetails
    destination
    destinationDetails
    etc
    If there is a one to many relationship, then the following would be true
    packages
    packageID
    package
    packageDetails
    etc
    destinations
    destinationID
    packageID
    destination
    destinationDetails
    etc
    The above assumes that there are many destinations to one package with the relationship coloured orange.
    Once you have the above correct you can apply your query as follows
    SELECT *
    FROM packages
    INNER JOIN destinations
    ON packages.packageID = destinations.packageID
    WHERE packages.packageID = %s
    ORDER BY destination ASC
    The above query will show all packages with relevant destinations

  • Help with a group query

    I have the following table
    EX_ID
    EX_NAME
    EX_SURNAME
    EX_FLAG
    1
    TOM
    JONES
    Y
    1
    JIM
    SLIM
    N
    1
    BO
    SELECTA
    Y
    2
    AIRES
    BEARS
    N
    2
    JIM
    DAVIES
    Y
    3
    PAUL
    BALL
    N
    3
    YOU
    KNOW
    N
    I need to create a query that only displays one of the ex_id’s, it doesn’t matter which one.  When the query has been run it will look like below:
    EX_ID
    EX_NAME
    EX_SURNAME
    EX_FLAG
    1
    TOM
    JONES
    Y
    2
    AIRES
    BEARS
    N
    3
    YOU
    KNOW
    N
    Can anyone help with this query?

    SELECT * FROM
    SELECT *,ROW_NUMBER () OVER (PARTITION BY ex_id ORDER BY (SELECT 0))
    FROM tbl
    ) AS Der WHERE rn=1
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

Maybe you are looking for