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

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.

  • How to do outer join select query for an APEX report

    Hello everyone,
    I am Ann.
    I have one select statement that calculate the statistics for one month(October 2012 in this example)
    select ph.phase_number
    , sum ( (case
    WHEN ph.date_finished IS NULL OR ph.date_finished > last_day(TO_DATE('Oct 2012','MON YYYY'))
    THEN last_day(TO_DATE('Oct 2012','MON YYYY'))
    ELSE ph.date_finished
    END )
    - ph.date_started + 1) / count(def.def_id) as avg_days
    from phase_membership ph
    inner join court_engagement ce on ph.mpm_eng_id = ce.engagement_id
    inner join defendant def on ce.defendant_id = def.def_id
    where def.active = 1
    and ph.date_started <= last_day(TO_DATE('Oct 2012','MON YYYY'))
    and ph.active = 1
    and UPPER(ce.court_name) LIKE '%'
    group by rollup(phase_number)
    Result is as below
    Phase_Number     AVG_DAYS
    Phase One     8.6666666666666667
    Phase Two     14.6
    Phase Three     12
         11.4615365
    I have other select list mainly list the months between two date value.
    select to_char(which_month, 'MON YYYY') as display_month
    from (
    select add_months(to_date('Aug 2012','MON YYYY'), rownum-1) which_month
    from all_objects
    where
    rownum <= months_between(to_date('Oct 2012','MON YYYY'), add_months(to_date('Aug 2012','MON YYYY'), -1))
    order by which_month )
    Query result is as below
    DISPLAY_MONTH
    AUG 2012
    SEP 2012
    OCT 2012
    Is there any way that I can join these two select statement above to generate a result like:
    Month          Phase Number     Avg days
    Aug 2012     Phase One     8.666
    Sep 2012     Phase One     7.66
    Oct 2012     Phase One     5.66
    Aug 2012     Phase Two     8.666
    Sep 2012     Phase Two     7.66
    Oct 2012     Phase Two     5.66
    Aug 2012     Phase Three     8.666
    Sep 2012     Phase Three     7.66
    Oct 2012     Phase Three     5.66
    Or
    Month          Phase Number     Avg days
    Aug 2012     Phase One     8.666
    Aug 2012     Phase Two     7.66
    Aug 2012     Phase Three     5.66
    Sep 2012     Phase One     8.666
    Sep 2012     Phase Two     7.66
    Sep 2012     Phase Three     5.66
    Oct 2012     Phase One     8.666
    Oct 2012     Phase Two     7.66
    Oct 2012     Phase Three     5.66
    And it can be order by either Phase Number or Month.
    My other colleague suggest I should use an left outer join but after trying so many ways, I am still stuck.
    One of the select I tried is
    select a.display_month,b.* from (
    select to_char(which_month, 'MON YYYY') as display_month
    from (
    select add_months(to_date('Aug 2012','MON YYYY'), rownum-1) which_month
    from all_objects
    where
    rownum <= months_between(to_date('Oct 2012','MON YYYY'), add_months(to_date('Aug 2012','MON YYYY'), -1))
    order by which_month )) a left outer join
    ( select to_char(ph.date_finished,'MON YYYY') as join_month, ph.phase_number
    , sum ( (case
    WHEN ph.date_finished IS NULL OR ph.date_finished > last_day(TO_DATE(a.display_month,'MON YYYY'))
    THEN last_day(TO_DATE(a.display_month,'MON YYYY'))
    ELSE ph.date_finished
    END )
    - ph.date_started + 1) / count(def.def_id) as avg_days
    from phase_membership ph
    inner join court_engagement ce on ph.mpm_eng_id = ce.engagement_id
    inner join defendant def on ce.defendant_id = def.def_id
    where def.active = 1
    and ph.date_started <= last_day(TO_DATE(a.display_month,'MON YYYY'))
    and ph.active = 1
    and UPPER(ce.court_name) LIKE '%'
    group by to_char(ph.date_finished,'MON YYYY') , rollup(phase_number)) b
    on a.display_month = b.join_month
    but then I get an error
    SQL Error: ORA-00904: "A"."DISPLAY_MONTH": invalid identifier
    I need to display a report on APEX with option for people to download at least CSV format.
    I already have 1 inteactive report in the page, so don’t think can add another interactive report without using the iframe trick.
    If any of you have any ideas, please help.
    Thanks a lot.
    Ann

    First of all, a huge thanks for following this Frank.
    I have just started working here, I think the Oracle version is 11g, but not sure.
    To run Oracle APEX version 4, I think they must have at least 10g R2.
    This report is a bit challenging for me.I has never worked with PARTITION before.
    About the select query you suggested, I run , and it seems working fine, but if I try this,
    it return error ORA-01843: not a valid month
    DEFINE startmonth = "Aug 2012";
    DEFINE endmonth   = "Oct 2012";
    WITH     all_months     AS
         select add_months(to_date('&startmonth','MON YYYY'), rownum-1) AS which_month
         ,      add_months(to_date('&startmonth','MON YYYY'), rownum  ) AS next_month
         from all_objects
         where
         rownum <= months_between(to_date('&endmonth','MON YYYY'), add_months(to_date('&startmonth','MON YYYY'), -1))
    select TO_CHAR (am.which_month, 'Mon YYYY')     AS month
    ,      ph.phase_number
    , sum ( (case
    WHEN ph.date_finished IS NULL OR ph.date_finished > last_day(TO_DATE(am.which_month,'MON YYYY'))
    THEN last_day(TO_DATE(am.which_month,'MON YYYY'))
    ELSE ph.date_finished
    END )
    - ph.date_started + 1) / count(def.def_id) as avg_days
    FROM           all_months          am
    LEFT OUTER JOIN  phase_membership  ph  PARTITION BY (ph.phase_number)
                                        ON  am.which_month <= ph.date_started
                               AND am.next_month  >  ph.date_started
                               AND ph.date_started <= last_day(TO_DATE(am.which_month,'MON YYYY'))  -- May not be needed
                               AND ph.active = 1
    LEFT OUTER join  court_engagement  ce  on  ph.mpm_eng_id = ce.engagement_id
                                        and ce.court_name IS NOT NULL  -- or something involving LIKE
    LEFT OUTER join  defendant         def on  ce.defendant_id = def.def_id
                                        AND def.active = 1
    group by rollup(phase_number, am.which_month)
    ORDER BY  am.which_month
    ,            ph.phase_number
    ;Here is the shorted versions of the three tables:
    A_DEFENDANT, A_ENGAGEMENT, A_PHASE_MEMBERSHIP
    CREATE TABLE "A_DEFENDANT"
        "DEF_ID"     NUMBER NOT NULL ENABLE,
        "FIRST_NAME" VARCHAR2(50 BYTE),
        "SURNAME"    VARCHAR2(20 BYTE) NOT NULL ENABLE,
        "DOB" DATE NOT NULL ENABLE,
        "ACTIVE" NUMBER(2,0) DEFAULT 1 NOT NULL ENABLE,
        CONSTRAINT "A_DEFENDANT_PK" PRIMARY KEY ("DEF_ID"))
    Sample Data
    Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (101,'Joe','Bloggs',to_date('12/12/99','DD/MM/RR'),1);
    Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (102,'John','Smith',to_date('20/05/00','DD/MM/RR'),1);
    Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (103,'Jane','Black',to_date('15/02/98','DD/MM/RR'),1);
    Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (104,'Minnie','Mouse',to_date('13/12/88','DD/MM/RR'),0);
    Insert into A_DEFENDANT (DEF_ID,FIRST_NAME,SURNAME,DOB,ACTIVE) values (105,'Daisy','Duck',to_date('05/08/00','DD/MM/RR'),1);
    CREATE TABLE "A_ENGAGEMENT"
        "ENGAGEMENT_ID" NUMBER NOT NULL ENABLE,
        "COURT_NAME"    VARCHAR2(50 BYTE) NOT NULL ENABLE,
        "DATE_REFERRED" DATE,
        "DETERMINATION_HEARING_DATE" DATE,
        "DATE_JOINED_COURT" DATE,
        "DATE_TREATMENT_STARTED" DATE,
        "DATE_TERMINATED" DATE,
        "TERMINATION_TYPE" VARCHAR2(50 BYTE),
        "ACTIVE"           NUMBER(2,0) DEFAULT 1 NOT NULL ENABLE,
        "DEFENDANT_ID"     NUMBER,
        CONSTRAINT "A_ENGAGEMENT_PK" PRIMARY KEY ("ENGAGEMENT_ID"))
    Insert into A_ENGAGEMENT (ENGAGEMENT_ID,COURT_NAME,DATE_REFERRED,DETERMINATION_HEARING_DATE,DATE_JOINED_COURT,DATE_TREATMENT_STARTED,DATE_TERMINATED,TERMINATION_TYPE,ACTIVE,DEFENDANT_ID) values (1,'AA',to_date('12/08/12','DD/MM/RR'),null,to_date('12/08/12','DD/MM/RR'),null,null,null,1,101);
    Insert into A_ENGAGEMENT (ENGAGEMENT_ID,COURT_NAME,DATE_REFERRED,DETERMINATION_HEARING_DATE,DATE_JOINED_COURT,DATE_TREATMENT_STARTED,DATE_TERMINATED,TERMINATION_TYPE,ACTIVE,DEFENDANT_ID) values (2,'BB',to_date('01/09/12','DD/MM/RR'),null,to_date('02/09/12','DD/MM/RR'),null,null,null,1,102);
    Insert into A_ENGAGEMENT (ENGAGEMENT_ID,COURT_NAME,DATE_REFERRED,DETERMINATION_HEARING_DATE,DATE_JOINED_COURT,DATE_TREATMENT_STARTED,DATE_TERMINATED,TERMINATION_TYPE,ACTIVE,DEFENDANT_ID) values (3,'AA',to_date('02/09/12','DD/MM/RR'),null,to_date('15/09/12','DD/MM/RR'),null,null,null,1,103);
    Insert into A_ENGAGEMENT (ENGAGEMENT_ID,COURT_NAME,DATE_REFERRED,DETERMINATION_HEARING_DATE,DATE_JOINED_COURT,DATE_TREATMENT_STARTED,DATE_TERMINATED,TERMINATION_TYPE,ACTIVE,DEFENDANT_ID) values (4,'BB',to_date('01/10/12','DD/MM/RR'),null,to_date('02/10/12','DD/MM/RR'),null,null,null,1,105);
    CREATE TABLE "A_PHASE_MEMBERSHIP"
        "MPM_ID"       NUMBER NOT NULL ENABLE,
        "MPM_ENG_ID"   NUMBER NOT NULL ENABLE,
        "PHASE_NUMBER" VARCHAR2(50 BYTE),
        "DATE_STARTED" DATE NOT NULL ENABLE,
        "DATE_FINISHED" DATE,
        "NOTES"  VARCHAR2(2000 BYTE),
        "ACTIVE" NUMBER(2,0) DEFAULT 1 NOT NULL ENABLE,
        CONSTRAINT "A_PHASE_MEMBERSHIP_PK" PRIMARY KEY ("MPM_ID"))
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (1,1,'PHASE ONE',to_date('15/09/12','DD/MM/RR'),to_date('20/09/12','DD/MM/RR'),null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (2,1,'PHASE TWO',to_date('21/09/12','DD/MM/RR'),to_date('29/09/12','DD/MM/RR'),null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (3,2,'PHASE ONE',to_date('12/09/12','DD/MM/RR'),null,null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (4,3,'PHASE ONE',to_date('20/09/12','DD/MM/RR'),to_date('01/10/12','DD/MM/RR'),null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (5,3,'PHASE TWO',to_date('02/10/12','DD/MM/RR'),to_date('15/10/12','DD/MM/RR'),null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (6,4,'PHASE ONE',to_date('03/10/12','DD/MM/RR'),to_date('10/10/12','DD/MM/RR'),null,1);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (7,3,'PHASE THREE',to_date('17/10/12','DD/MM/RR'),null,null,0);
    Insert into A_PHASE_MEMBERSHIP (MPM_ID,MPM_ENG_ID,PHASE_NUMBER,DATE_STARTED,DATE_FINISHED,NOTES,ACTIVE) values (8,1,'PHASE THREE',to_date('30/09/12','DD/MM/RR'),to_date('16/10/12','DD/MM/RR'),null,1);
    The requirements are:
    The user must be able to request the extract for one or more calendar months, e.g.
    May 2013
    May 2013 – Sep 2013.
    The file must contain a separate row for each calendar month in the requested range. Each row must contain the statistics computed for that calendar month.
    The file must also include a row of totals.
    The user must be able to request the extract for either Waitakere or Auckland or Consolidated (both courts’ statistics accumulated).
    Then the part that I am stuck is
    For each monitoring phase:
    Phase name (e.g. “Phase One”)
    Avg_time_in_phase_all_particip
    for each phase name,
    Add up days in each “phase name” Monitoring Phase, calculated as:
    If Monitoring Phase.Date Finished is NULL or > month end date,
    +(*Month end date* Minus Monitoring Phase.Date Started Plus 1)+
    Otherwise (phase is complete)
    +(Monitoring Phase.Date Finished Minus Monitoring Phase.Date Started Plus 1.)+
    Divide by the numbers of all participants who have engaged in “phase name”.
    This is the words of the Business Analyst,
    I try to do as required but still struggle to identify end_month for the above formula to display for the range of months.
    Of course, I can write two nested cursor. The first one run the list of month, then for each month, run the parameterised report.
    But I prefer if possible just use SQL statements, or at least a PL/SQL but return a query.
    With this way, I can create an APEX report, and use their CSV Extract function.
    Yes, you are right, court_name is one of the selection parameters.
    And the statistics is not exactly for one month. It is kind of trying to identify all phases that are running through the specified month (even phase.date_started is before the month start).
    This is the reason why I put the condition AND ph.date_started <= last_day(TO_DATE('Oct 2012','MON YYYY')) (otherwise I get negative avg_days)
    User can choose either one court "AA" or "BB" or combined which is all figures.
    Sorry for bombarding you a lot of information.
    Thanks a lot, again.
    Edited by: Ann586341 on Oct 29, 2012 9:57 PM
    Edited by: Ann586341 on Oct 29, 2012 9:59 PM

  • Help reagrding the selection query

    Hi All...
    I have     VBELN
         LFART
         VKORG
         KUNNR
         ERDAT
         LFDAT
         VSTEL
         ROUTE in my selection-screen. All the fields are from LIKP.
    Now I need to add one more field LAND1 from the table VBPA in the selection screen.
    This is my logic to filter the previous requirement. Now how to validate the LAND1?
    -> LIKP
      select vbeln
              into table i_likp
              from likp
              where vbeln in s_vbeln
                and lfart in s_lfart
                and vkorg in s_vkorg
                and kunnr in s_kunnr
                and erdat in s_erdat
                and lfdat in s_lfdat
                and vstel = p_vstel
                and route in s_route.
      if sy-subrc = 0.
    -> LIPS
        select vbeln posnr bwtar volum
                into table i_lips
                from lips
                for all entries in i_likp
                where vbeln = i_likp-vbeln.
    Please help me in that. I will reward u with good points.
    Reagrds
    Arjun Jain

    For LAND1 validation do as below.
    AT SELECTION-SCREEN ON s_land1.
    SELECT land1 FROM t005
                           into t005-land1
                           where land1 IN s_land1.
    if sy-subrc NE 0.
    message e000 WITH 'Enter valid Land value'.
    endif.
    For the query u can use join
    select a~vbeln  b~posnr b~bwtar b~volum
             from likp as a inner join  lips as b
             on a~vbeln =b~vbeln
             into table i_tab
             where a~vbeln in s_vbeln
              and a~lfart in s_lfart
              and a~vkorg in s_vkorg
              and a~kunnr in s_kunnr
              and a~erdat in s_erdat
             and a~lfdat in s_lfdat
            and a~vstel = p_vstel
            and a~route in s_route.
    This will solve ur problem.
    U can reward for the helpful answers.

  • 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

  • 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

  • Pls help me in select query......

    My problem is...
    I have to use a select query in such a manner  that i  can compare the last 8 characters or ignore the first one...

    Hi Aarif,
    Try this :
    parameters :
      p_field1(30)  type c.
    Data :
      w_string(8) type c,
      w_firstchar type c,
      t_itab ......,
      fs_itab like line of itab.
    w_string = p_field1+22(8)      " passing last 8 chars into w_string
    w_firstchar = p_field1+0(1).
    select *
       from DataTab Name
       into  table IntTab Name
    where <field name> eq w_string
          or  <field name> ne w_firstchar.
    If you are accepting the value from user then first pass the last 8 characters into w_string and in your select query get the fields where the value is equal to w_string. And pass the first character into another field and to ignore write NE W_FIRSTCHAR.
    There can be other methods also. This is one of the ways.
    Regards,
    Swapna.
    Edited by: NagaSwapna Thota on Jul 19, 2008 9:23 AM

  • Inner Join Select query

    hello all,
    Below is a inner join query
        SELECT aebeln aebelp apackno bzekkn b~ps_psp_pnr
                     FROM ( ( ekpo AS a INNER JOIN ekkn AS b
                              ON aebeln = bebeln
                              AND  aebelp = bebelp )
                             INNER JOIN prps AS c
                              ON bps_psp_pnr = cpspnr )
                     INTO TABLE t_wbspo
                      WHERE a~ebeln IN s_ebeln
                       AND  c~psphi IN s_psphi
                       AND  stufe = c_task.
    I want to modify this select and put one more join on ekkn-aufnr
    and aufk-afunr .
    Now for this i write the below code
      SELECT aebeln aebelp apackno bzekkn bps_psp_pnr baufnr
               FROM ( ( ( ekpo AS a INNER JOIN ekkn AS b
                        ON aebeln = bebeln
                        AND  aebelp = bebelp )
                       INNER JOIN prps AS c
                        ON bps_psp_pnr = cpspnr )
                        INNER JOIN aufk AS d
                        ON baufnr = daufnr )
               INTO TABLE t_wbspo
                WHERE a~ebeln IN s_ebeln
                 AND  c~psphi IN s_psphi
                 AND  d~aufnr IN s_aufnr
        AND  stufe = c_task.
    By the above way does it puts a join on ekkn-aufnr and aufk-aufnr ?
    Is the above way the right way to do it ?
    Please confirm
    regards

    Hello Bhanu,
    Do you face any performance issue? Query looks good now, further you can refer to following threads to know more on JOIN-
    Re: Inner join
    http://help.sap.com/saphelp_nw04/helpdata/en/cf/21ec77446011d189700000e8322d00/frameset.htm
    Thank You,
    Nishikant Kumbhar.

  • Help in Pivot select Query

    Hello,
    Oracle:Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Prod
    OS: Windows XP SP-3
    create table dws(coll_cd varchar2(6),tot float,dtcd varchar2(2),distname varchar2(20),schtype varchar2(1),year varchar2(4));
    insert into dws values('01001',103,'01','DIST1','1','2008');
    insert into dws values('01001',23,'01','DIST1','1','2007');
    insert into dws values('01115',39,'02','DIST2','2','2008');
    insert into dws values('01715',39,'02','DIST2','1','2007');
    insert into dws values('01415',120,'02','DIST2','2','2008');
    insert into dws values('01749',200,'01','DIST1','1','2006');
    insert into dws values('01449',200,'01','DIST1','2','2006');
    Year column will contain only 2006,2007 and 2008 and only 1,2 in schtype column.
    Output required: (Count of records as per year and schtype group by dtcd)
                                         2008                          2007                             2006
    DTCD    DISTNAME           TYPE1     TYPE2     TOTAL      TYPE1    TYPE2     TOTAL         TYPE1    TYPE2    TOTAL
    01      DIST1                1         0         1          1        0         1             1       1        2      
    02      DIST2                0         2         2          1        0         1             0       0        0I tried by following:
    select dtcd,
    sum(case when(year='2008' and schtype='1') then 1 else 0 end) A,
    sum(case when(year='2008' and schtype='2') then 1 else 0 end) B,
    sum(case when(year='2007' and schtype='1') then 1 else 0 end) C,
    sum(case when(year='2007' and schtype='2') then 1 else 0 end) D,
    sum(case when(year='2006' and schtype='1') then 1 else 0 end) E,
    sum(case when(year='2006' and schtype='2') then 1 else 0 end) F
    from dws group by dtcd,govtpvtn order by 1
    but it is not which i want.
    Please help me how to write the query to get the required output.
    Thanks & Regards
    Girish Sharma
    Edited by: Girish Sharma on Dec 22, 2008 10:28 PM

    There could be several ways to frame this query. One of the ways could be as follows:
    SELECT
    DTCD,
    DISTNAME,
    (SELECT COUNT(1) FROM DWS B WHERE A.DTCD = B.DTCD AND A.DISTNAME = B.DISTNAME AND B.YEAR = '2008' AND B.SCHTYPE = '1') TYPE1_2008,
    (SELECT COUNT(1) FROM DWS B WHERE A.DTCD = B.DTCD AND A.DISTNAME = B.DISTNAME AND B.YEAR = '2008' AND B.SCHTYPE = '2') TYPE1_2008,
    (SELECT COUNT(1) FROM DWS B WHERE A.DTCD = B.DTCD AND A.DISTNAME = B.DISTNAME AND B.YEAR = '2008') TOTAL_2008,
    (SELECT COUNT(1) FROM DWS B WHERE A.DTCD = B.DTCD AND A.DISTNAME = B.DISTNAME AND B.YEAR = '2007' AND B.SCHTYPE = '1') TYPE1_2007,
    (SELECT COUNT(1) FROM DWS B WHERE A.DTCD = B.DTCD AND A.DISTNAME = B.DISTNAME AND B.YEAR = '2007' AND B.SCHTYPE = '2') TYPE1_2007,
    (SELECT COUNT(1) FROM DWS B WHERE A.DTCD = B.DTCD AND A.DISTNAME = B.DISTNAME AND B.YEAR = '2007') TOTAL_2007 ,
    (SELECT COUNT(1) FROM DWS B WHERE A.DTCD = B.DTCD AND A.DISTNAME = B.DISTNAME AND B.YEAR = '2006' AND B.SCHTYPE = '1') TYPE1_2006,
    (SELECT COUNT(1) FROM DWS B WHERE A.DTCD = B.DTCD AND A.DISTNAME = B.DISTNAME AND B.YEAR = '2006' AND B.SCHTYPE = '2') TYPE1_2006,
    (SELECT COUNT(1) FROM DWS B WHERE A.DTCD = B.DTCD AND A.DISTNAME = B.DISTNAME AND B.YEAR = '2006') TOTAL_2006   
    FROM
    DWS A
    GROUP BY DTCD, DISTNAME
    DT DISTNAME             TYPE1_2008 TYPE1_2008 TOTAL_2008 TYPE1_2007 TYPE1_2007 TOTAL_2007 TYPE1_2006 TYPE1_2006 TOTAL_2006   
    01 DIST1                         1          0          1          1          0          1          1          1          2   
    02 DIST2                         0          2          2          1          0          1          0          0          0   

  • Need help for SQL SELECT query to fetch XML records from Oracle tables having CLOB field

    Hello,
    I have a scenario wherein i need to fetch records from several oracle tables having CLOB fields(which is holding XML) and then merge them logically to form a hierarchy XML. All these tables are related with PK-FK relationship. This XML hierarchy is having 'OP' as top-most root node and ‘DE’ as it’s bottom-most node with One-To-Many relationship. Hence, Each OP can have multiple GM, Each GM can have multiple DM and so on.
    Table structures are mentioned below:
    OP:
    Name                             Null                    Type        
    OP_NBR                    NOT NULL      NUMBER(4)    (Primary Key)
    OP_DESC                                        VARCHAR2(50)
    OP_PAYLOD_XML                           CLOB       
    GM:
    Name                          Null                   Type        
    GM_NBR                  NOT NULL       NUMBER(4)    (Primary Key)
    GM_DESC                                       VARCHAR2(40)
    OP_NBR               NOT NULL          NUMBER(4)    (Foreign Key)
    GM_PAYLOD_XML                          CLOB   
    DM:
    Name                          Null                    Type        
    DM_NBR                  NOT NULL         NUMBER(4)    (Primary Key)
    DM_DESC                                         VARCHAR2(40)
    GM_NBR                  NOT NULL         NUMBER(4)    (Foreign Key)
    DM_PAYLOD_XML                            CLOB       
    DE:
    Name                          Null                    Type        
    DE_NBR                     NOT NULL           NUMBER(4)    (Primary Key)
    DE_DESC                   NOT NULL           VARCHAR2(40)
    DM_NBR                    NOT NULL           NUMBER(4)    (Foreign Key)
    DE_PAYLOD_XML                                CLOB    
    +++++++++++++++++++++++++++++++++++++++++++++++++++++
    SELECT
    j.op_nbr||'||'||j.op_desc||'||'||j.op_paylod_xml AS op_paylod_xml,
    i.gm_nbr||'||'||i.gm_desc||'||'||i.gm_paylod_xml AS gm_paylod_xml,
    h.dm_nbr||'||'||h.dm_desc||'||'||h.dm_paylod_xml AS dm_paylod_xml,
    g.de_nbr||'||'||g.de_desc||'||'||g.de_paylod_xml AS de_paylod_xml,
    FROM
    DE g, DM h, GM i, OP j
    WHERE
    h.dm_nbr = g.dm_nbr(+) and
    i.gm_nbr = h.gm_nbr(+) and
    j.op_nbr = i.op_nbr(+)
    +++++++++++++++++++++++++++++++++++++++++++++++++++++
    I am using above SQL select statement for fetching the XML records and this gives me all related xmls for each entity in a single record(OP, GM, DM. DE). Output of this SQL query is as below:
    Current O/P:
    <resultSet>
         <Record1>
              <OP_PAYLOD_XML1>
              <GM_PAYLOD_XML1>
              <DM_PAYLOD_XML1>
              <DE_PAYLOD_XML1>
         </Record1>
         <Record2>
              <OP_PAYLOD_XML2>
              <GM_PAYLOD_XML2>
              <DM_PAYLOD_XML2>
              <DE_PAYLOD_XML2>
         </Record2>
         <RecordN>
              <OP_PAYLOD_XMLN>
              <GM_PAYLOD_XMLN>
              <DM_PAYLOD_XMLN>
              <DE_PAYLOD_XMLN>
         </RecordN>
    </resultSet>
    Now i want to change my SQL query so that i get following output structure:
    <resultSet>
         <Record>
              <OP_PAYLOD_XML1>
              <GM_PAYLOD_XML1>
              <GM_PAYLOD_XML2> .......
              <GM_PAYLOD_XMLN>
              <DM_PAYLOD_XML1>
              <DM_PAYLOD_XML2> .......
              <DM_PAYLOD_XMLN>
              <DE_PAYLOD_XML1>
              <DE_PAYLOD_XML2> .......
              <DE_PAYLOD_XMLN>
         </Record>
         <Record>
              <OP_PAYLOD_XML2>
              <GM_PAYLOD_XML1'>
              <GM_PAYLOD_XML2'> .......
              <GM_PAYLOD_XMLN'>
              <DM_PAYLOD_XML1'>
              <DM_PAYLOD_XML2'> .......
              <DM_PAYLOD_XMLN'>
              <DE_PAYLOD_XML1'>
              <DE_PAYLOD_XML2'> .......
              <DE_PAYLOD_XMLN'>
         </Record>
    <resultSet>
    Appreciate your help in this regard!

    Hi,
    A few questions :
    How's your first query supposed to give you an XML output like you show ?
    Is there something you're not telling us?
    What's the content of, for example, <OP_PAYLOD_XML1> ?
    I don't think it's a good idea to embed the node level in the tag name, it would make much sense to expose that as an attribute.
    What's the db version BTW?

  • Help needed in select query

    Hi,
    I need to select the max time for the transaction using the below query. I’m able to get the o/p. Here the problem is I need to fetch the corrletorid (primary key) as well. if try to get that I’m getting the o/p like case2.
    I want the o/p to be like case 1 with the corrleator id . plz help me to get the o/p.
    Case 1: select b.TransactionName, max(to_char(b.duration, 'mm/dd/yyyy hh24:mi:ss.ff')) as average from trandetails a,subtrandetails b where a.CORRELATORID=b.PCORRELATORID and b.PCORRELATORID='11' group by b.transactionname
    TRANSACTIONNAME MAXTIME
    FINT3 12/10/2007 19:53:09.042000
    FINT 12/10/2007 19:31:07.042000
    FINT2 12/10/2007 19:31:07.042000
    SQL> /
    Case 2: select b.TransactionName,b.correlatorid, max(to_char(b.duration, 'mm/dd/yyyy hh24:mi:ss.ff')) as average from trandetails a,subtrandetails b where a.CORRELATORID=b.PCORRELATORID and b.PCORRELATORID='11' group by b.transactionname,b.correlatorid
    SQL> /
    TRANSACTIONNAME CORRELATORID AVERAGE
    FINT2 102 12/10/2007 19:31:07.042000
    FINT3 108 12/10/2007 19:53:09.042000
    FINT3 103 12/10/2007 19:31:07.042000
    FINT 101 12/10/2007 19:31:07.042000
    in the above output i should have only record(max time) for FINT3.
    Thank

    Sharma,
    Please find the below sample data(insert stmt and create table):
    ======================================
    create table trandetails(
    correlatorid varchar2(20) CONSTRAINT correlatorid_FKey REFERENCES Subtrandetails(correlatorid),
    username varchar2(25) NOT NULL,
    applicationname varchar2(25) NOT NULL,CONSTRAINT composite1_pkey1 PRIMARY KEY(correlatorid ,applicationname));
    create table Subtrandetails(
    correlatorid varchar2(20) PRIMARY KEY,
    PCORRELATORID      varchar2(20),
    TransactionName varchar2(25) NOT NULL,
    Machinename varchar2(15) NOT NULL,
    STARTDATE timestamp NOT NULL,
    ENDDATE timestamp NOT NULL,
    SourceName varchar2(25),
    FunctionName varchar2(25),
    LOC number(5),
    CONTEXTPROPERTY1 varchar2(25),
    CONTEXTPROPERTY2 varchar2(25),
    CONTEXTPROPERTY3 varchar2(25),
    TransactionStatus varchar2(25) NOT NULL CONSTRAINT Transaction1_Status_chk Check (TransactionStatus in ('Success', 'Failure', 'Abort')));
    INSERT INTO trandetails VALUES ('11','FINAPP','ANUAPP1');
    INSERT INTO trandetails VALUES ('13','FINTEST','ANUAPP2');
    INSERT INTO
    Subtrandetails(correlatorid,PCORRELATORID ,TransactionName,Machinename,STARTDATE,ENDDATE ,TransactionStatus )
    VALUES ('10','1','ARM','blrkec95931d','10-DEC-07 03.24.07.042000 PM','10-DEC-07 03.31.07.042000 PM','Success');
    INSERT INTO
    Subtrandetails(correlatorid,PCORRELATORID ,TransactionName,Machinename,STARTDATE,ENDDATE ,TransactionStatus )
    VALUES ('11','1','ARM1','blrkec95931d','10-DEC-07 04.24.07.042000 PM','10-DEC-07 04.31.07.042000 PM','Success');
    INSERT INTO
    Subtrandetails(correlatorid,PCORRELATORID ,TransactionName,Machinename,STARTDATE,ENDDATE ,TransactionStatus )
    VALUES ('12','1','ARM2','blrkec95931d','10-DEC-07 05.24.07.042000 PM','10-DEC-07 05.31.07.042000 PM','Success');
    INSERT INTO
    Subtrandetails(correlatorid,PCORRELATORID ,TransactionName,Machinename,STARTDATE,ENDDATE ,TransactionStatus )
    VALUES ('13','1','ARM3','blrkec95931d','10-DEC-07 06.24.07.042000 PM','10-DEC-07 06.31.07.042000 PM','Success');
    INSERT INTO
    Subtrandetails(correlatorid,PCORRELATORID ,TransactionName,Machinename,STARTDATE,ENDDATE ,TransactionStatus )
    VALUES ('14','1','ARM4','blrkec95931d','10-DEC-07 07.24.07.042000 PM','10-DEC-07 07.31.07.042000 PM','Success');
    INSERT INTO
    Subtrandetails(correlatorid,PCORRELATORID ,TransactionName,Machinename,STARTDATE,ENDDATE ,TransactionStatus )
    VALUES ('101','11','FINT','blrkec95931d','10-DEC-07 07.24.07.042000 PM','10-DEC-07 07.31.07.042000 PM','Success');
    INSERT INTO
    Subtrandetails(correlatorid,PCORRELATORID ,TransactionName,Machinename,STARTDATE,ENDDATE ,TransactionStatus )
    VALUES ('102','11','FINT2','blrkec95931d','10-DEC-07 07.24.07.042000 PM','10-DEC-07 07.31.07.042000 PM','Success');
    INSERT INTO
    Subtrandetails(correlatorid,PCORRELATORID ,TransactionName,Machinename,STARTDATE,ENDDATE ,TransactionStatus )
    VALUES ('103','11','FINT3','blrkec95931d','10-DEC-07 07.24.07.042000 PM','10-DEC-07 07.31.07.042000 PM','Success');
    INSERT INTO
    Subtrandetails(correlatorid,PCORRELATORID ,TransactionName,Machinename,STARTDATE,ENDDATE ,TransactionStatus )
    VALUES ('104','13','SAP1','blrkec95931d','10-DEC-07 07.24.07.042000 PM','10-DEC-07 07.31.07.042000 PM','Success');
    INSERT INTO
    Subtrandetails(correlatorid,PCORRELATORID,TransactionName,Machinename,STARTDATE,ENDDATE ,TransactionStatus )
    VALUES ('105','13','SAP2','blrkec95931d','10-DEC-07 07.24.07.042000 PM','10-DEC-07 07.31.07.042000 PM','Success');
    INSERT INTO
    Subtrandetails(correlatorid,PCORRELATORID ,TransactionName,Machinename,STARTDATE,ENDDATE ,TransactionStatus )
    VALUES ('106','13','SAP3','blrkec95931d','10-DEC-07 07.24.07.042000 PM','10-DEC-07 07.31.07.042000 PM','Success');
    INSERT INTO
    Subtrandetails(correlatorid,PCORRELATORID ,TransactionName,Machinename,STARTDATE,ENDDATE ,TransactionStatus )
    VALUES ('107','13','SAP2','blrkec95931d','10-DEC-07 07.2.10.042350 PM','10-DEC-07 07.50.10.042050 PM','Success');
    INSERT INTO
    Subtrandetails(correlatorid,PCORRELATORID ,TransactionName,Machinename,STARTDATE,ENDDATE ,TransactionStatus )
    VALUES ('108','11',' FINT3 ','blrkec95931d','10-DEC-07 07.16.07.042000 PM','10-DEC-07 07.53.09.042000 PM','Success');
    INSERT INTO
    Subtrandetails(correlatorid,PCORRELATORID ,TransactionName,Machinename,STARTDATE,ENDDATE ,TransactionStatus )
    VALUES ('109','108','FINT3','blrkec95931d','10-DEC-07 07.20.07.042000 PM','10-DEC-07 07.59.09.042000 PM','Success');
    INSERT INTO
    Subtrandetails(correlatorid,PCORRELATORID ,TransactionName,Machinename,STARTDATE,ENDDATE ,TransactionStatus )
    VALUES ('110','108','FINT3','blrkec95931d','10-DEC-07 07.18.07.042000 PM','10-DEC-07 07.57.09.042000 PM','Success');
    INSERT INTO
    Subtrandetails(correlatorid,PCORRELATORID ,TransactionName,Machinename,STARTDATE,ENDDATE ,TransactionStatus )
    VALUES ('111','108','FINT4','blrkec95931d','10-DEC-07 07.18.07.042000 PM','10-DEC-07 07.57.09.042000 PM','Success');
    INSERT INTO
    Subtrandetails(correlatorid,PCORRELATORID ,TransactionName,Machinename,STARTDATE,ENDDATE ,TransactionStatus )
    VALUES ('112','108','FINT5','blrkec95931d','10-DEC-07 07.18.07.042000 PM','10-DEC-07 07.57.09.042000 PM','Success');
    INSERT INTO
    Subtrandetails(correlatorid,PCORRELATORID ,TransactionName,Machinename,STARTDATE,ENDDATE ,TransactionStatus )
    VALUES ('113','108','FINT6','blrkec95931d','10-DEC-07 07.18.07.042000 PM','10-DEC-07 07.57.09.042000 PM','Success');
    INSERT INTO
    Subtrandetails(correlatorid,PCORRELATORID ,TransactionName,Machinename,STARTDATE,ENDDATE ,TransactionStatus )
    VALUES ('114','108','FINT7','blrkec95931d','10-DEC-07 07.18.07.042000 PM','10-DEC-07 07.57.09.042000 PM','Success');
    ======================================
    Thanks.

  • 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 :-(

  • Help needed in select query to take date

    Hello,
    I am using Oracle 11g.
    I am using this query
    select to_date(to_char(to_date((SOURCE_MONTH||'-'||SOURCE_YEAR),'MM-YYYY'),'Mon-YYYY'),'MON-YYYY') date_
    from tab1 a,tab2 b
    where b.col2=a.col1;
    I have a table with 2 separate varchar columns month and year,
    I want to insert the data into another table which has the col type as timestamp.
    This query gives me the data as
    01-NOV-06 but
    i want the data as
    01-NOV-2006
    What should i do for that?
    Thanks

    First, get rid of the extra conversions from date to char and back to date:
    select to_date((SOURCE_MONTH||'-'||SOURCE_YEAR),'MM-YYYY'),'Mon-YYYY')
    from tab1 a,tab2 b
    where b.col2=a.col1;Now, your data is safely rendered as a DATE. It knows the full year (i.e.2006). You are just not seeing it formatted the way you like. You could
    alter session set nls_date_format = 'mm/dd/yyyy hh24:mi:ss';or give the explicit format you want when you query it (with TO_CHAR).
    Please read and understand about DATE datatypes....
    http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/sql_elements001.htm#i54330
    In particular, search that page for: "DATE Datatype "

  • 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

  • Help need in selection query

    Hi ,
    I have a field(test) in ztable(zxxx) whose length is 12 char and while updating it
    only 10 digits were updated and there are no zeros in front of the value in order to make it
    12 digit.
    Now i need this parameter to be included in another program selection screen.
    Now i have given it as
    parameter :  test(12) type n.
    it works fine when it has an entry , when it is blank i has to retrieve all records but in this case
    i won't because it has a value of 000000000000
    noe when i declare like this
    paramter : test like zxxx-test.
    when my input is 123456, it won't fetch me any value because it has to be 0000123456 because it has been updated like in the table.
    There was a purpose in updating this way.
    Now my code is like this
    parameters : test(10) type n.
    select-options :   kostl for zxxx-kostl NO-EXTENSION NO INTERVALS,
          p_uname for zxxx-uname NO-EXTENSION NO INTERVALS.
    if test is initial.
    select * from zxxx into table itab where kostl in kostl and uname in p_uname.
    else.
    select * from zxxx into table itab where aufnr  = order and
                                   kostl in kostl and uname in p_uname.
    endif
    PLEASE SUGGEST ME IF THERE IS AN ALTERNATE BETTER WAY.
    or this is the best way
    Thanks

    Hi
    as per my knowledge what you have done is right.
    Thanks
    KAJOL

Maybe you are looking for

  • Actions in Warranty Claim

    Hi, In creation of Warranty Claim using T Code WTY, we have Action A200 (Check Warranty (All)). If I trigger this action manually and if the Equipment is Out Of Warranty, I want the system to throw Error for a particular Warranty Type. How do I confi

  • How to add properties in JMS

    Hello, i have created a proxy and business services that send JMS to a queue. But i don't find how to set a new jms perpertie. Thanks for your help.

  • Trying to print to our Color Copy machine on Mavericks

    I am attempting to print to our color copier (Imagistics CM2522) using Mavericks.  I can print from Chrome, Firefox, Adobe Reader; but when I try Safari, Pages, Preview I get the following error: Process:         Preview [3053] Path:            /Appl

  • HT1541 Hi i am trying to redeem a voucher on my mobile. It comes up with an error message

    I tried to redeem a voucher but it comes up with an error message. It asked to scan voucher but I can't find the button to take a photo.

  • INdividual Frames disappear

    I am having problems with the individual frames on the timeline disappearing. I have reset the settings multiple times and cannot find any settings to put the individual frames back on. It seems like a system wide preference because all users on the