Need to merge 3 quiries as one query

Hi All,
Please help me on below issue.
Below 3 queries are written in a 3 procedures and all 3 quiries are accessing same table and slight difference only is there.Please help to merge 3 queries to 1 query for hitting database only once.
*** are displaying instead of C U M in below posting thred ,i don't know why it is.Please where ever 3 starts are there assume that is C U M1st one
INSERT INTO WASTE_PREF_DOW
        (PERIOD_KEY,
        CONSUMER_KEY,
        PREFDOW,
        FIN_SCOR_DOW,
        GRANULAR
SELECT STARTPERIOD PERIOD_KEY,CONSUMER_KEY,DOW_KEY  PREFDOW,nvl(FIN_SCOR_DOW,-1),GRANULAR1 GRANULAR FROM
SELECT CONSUMER_KEY,DOW_KEY,FIN_SCOR_DOW,
ROW_NUMBER() OVER ( PARTITION BY CONSUMER_KEY ORDER BY FIN_SCOR_DOW DESC,DOW_KEY ) RNO
FROM
SELECT CONSUMER_KEY,DOW_KEY,SUM(SCORE_SERVICE_WEIGHT) FIN_SCOR_DOW FROM
SELECT DOW_KEY,CONSUMER_KEY,SERVICE_KEY,DUR,TRAN,VOLU,TOT_DUR, CUM_DUR,TOT_TRAN,CUM_TRAN,TOT_VOL,CUM_VOL,SCORE_DUR,SCORE_TRAN,SCORE_VOL,
1*NVL(SCORE_DUR,0)+1*NVL(SCORE_TRAN,0)+1*NVL(SCORE_VOL,0) TOT_SCOR ,
CASE
WHEN SERVICE_KEY= 0 THEN
1*SCORE_DUR
WHEN SERVICE_KEY IN ('1','3') THEN
1*SCORE_TRAN
WHEN SERVICE_KEY  = 2 THEN
1*SCORE_VOL
END SCORE_SERVICE_WEIGHT FROM
select DOW_KEY,consumer_key,service_key,sumDUR dur,SUMTRAN tran,sumVOL volu,
tot_dur,cum_dur,tot_tran,cum_tran,tot_vol,cum_vol,
case
when tot_dur > 0 then
cum_dur*100/tot_dur
end score_dur,
case
when tot_tran > 0 then
cum_tran*100/tot_tran
end score_tran,
case
when tot_vol > 0 then
cum_vol*100/tot_vol
end  score_vol
from
SELECT CONSUMER_KEY,SERVICE_KEY,DOW_KEY,SUMDUR,SUMTRAN,SUMVOL,SUM(SUMDUR) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ) TOT_DUR,
SUM(SUMDUR) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ORDER BY SUMDUR,DOW_KEY) CUM_DUR,
--SUM(SUMDUR) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ORDER BY SUMDUR,DOW_KEY,RNO) CUM_DUR,
SUM(SUMTRAN) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ) TOT_TRAN,
SUM(SUMTRAN) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ORDER BY SUMTRAN,DOW_KEY) CUM_TRAN,
--SUM(SUMDUR) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ORDER BY SUMDUR,DOW_KEY,RNO) CUM_DUR,
SUM(SUMVOL) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ) TOT_VOL,
SUM(SUMVOL) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ORDER BY SUMVOL,DOW_KEY) CUM_VOL
--SUM(SUMDUR) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ORDER BY SUMDUR,DOW_KEY,RNO) CUM_DUR,
FROM
SELECT CONSUMER_KEY,SERVICE_KEY, to_number(to_char(to_date(DATE_KEY,'YYYYMMDD'),'D')) DOW_KEY,
sum(SUM_OF_DURATION) sumdur,SUM(NO_OF_TRANSACTIONS) sumtran,sum(SUM_OF_VOLUME) sumvol
--ROW_NUMBER () OVER (ORDER BY CONSUMER_KEY) RNO
FROM SERVICE_FACTS_BY_DAY
WHERE DATE_KEY BETWEEN STARTPERIOD AND ENDPERIOD
group by CONSUMER_KEY,SERVICE_KEY,to_number(to_char(to_date(DATE_KEY,'YYYYMMDD'),'D'))
ORDER BY CONSUMER_KEY,SERVICE_KEY,to_number(to_char(to_date(DATE_KEY,'YYYYMMDD'),'D'))
GROUP BY CONSUMER_KEY,DOW_KEY
WHERE RNO=1;2nd one
INSERT INTO WASTE_PREF_POW
        (PERIOD_KEY,
        CONSUMER_KEY,
        PREFPOW,
        FIN_SCOR_POW,
        GRANULAR
SELECT STARTPERIOD PERIOD_KEY,CONSUMER_KEY,POW_KEY  PREFPOW,nvl(FIN_SCOR_POW,-1),GRANULAR1 GRANULAR FROM
SELECT CONSUMER_KEY,POW_KEY,FIN_SCOR_POW,
ROW_NUMBER() OVER ( PARTITION BY CONSUMER_KEY ORDER BY FIN_SCOR_POW DESC,POW_KEY ) RNO
FROM
SELECT CONSUMER_KEY,POW_KEY,SUM(SCORE_SERVICE_WEIGHT) FIN_SCOR_POW FROM
SELECT POW_KEY,CONSUMER_KEY,SERVICE_KEY,DUR,TRAN,VOLU,TOT_DUR,CUM_DUR,TOT_TRAN,CUM_TRAN,TOT_VOL,CUM_VOL,SCORE_DUR,SCORE_TRAN,SCORE_VOL,
1*NVL(SCORE_DUR,0)+1*NVL(SCORE_TRAN,0)+1*NVL(SCORE_VOL,0) TOT_SCOR ,
CASE
WHEN SERVICE_KEY= 0 THEN
1*SCORE_DUR
WHEN SERVICE_KEY IN ('1','3') THEN
1*SCORE_TRAN
WHEN SERVICE_KEY  = 2 THEN
1*SCORE_VOL
END SCORE_SERVICE_WEIGHT FROM
select POW_KEY,consumer_key,service_key,sumDUR dur,SUMTRAN tran,sumVOL volu,
tot_dur,cum_dur,tot_tran,cum_tran,tot_vol,cum_vol,
case
when tot_dur > 0 then
cum_dur*100/tot_dur
end score_dur,
case
when tot_tran > 0 then
cum_tran*100/tot_tran
end score_tran,
case
when tot_vol > 0 then
cum_vol*100/tot_vol
end  score_vol
from
SELECT CONSUMER_KEY,SERVICE_KEY,POW_KEY,SUMDUR,SUMTRAN,SUMVOL,SUM(SUMDUR) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ) TOT_DUR,
SUM(SUMDUR) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ORDER BY SUMDUR,POW_KEY) CUM_DUR,
--SUM(SUMDUR) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ORDER BY SUMDUR,DOW_KEY,RNO) CUM_DUR,
SUM(SUMTRAN) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ) TOT_TRAN,
SUM(SUMTRAN) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ORDER BY SUMTRAN,POW_KEY) CUM_TRAN,
--SUM(SUMDUR) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ORDER BY SUMDUR,DOW_KEY,RNO) CUM_DUR,
SUM(SUMVOL) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ) TOT_VOL,
SUM(SUMVOL) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ORDER BY SUMVOL,POW_KEY) CUM_VOL
--SUM(SUMDUR) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ORDER BY SUMDUR,DOW_KEY,RNO) CUM_DUR,
FROM
SELECT CONSUMER_KEY,SERVICE_KEY, DECODE (to_number(to_char(to_date(DATE_KEY,'YYYYMMDD'),'D')),6,0,7,0,1 ) POW_KEY,                                                                                            
sum(SUM_OF_DURATION) sumdur,SUM(NO_OF_TRANSACTIONS) sumtran,sum(SUM_OF_VOLUME) sumvol
--ROW_NUMBER () OVER (ORDER BY CONSUMER_KEY) RNO
FROM SERVICE_FACTS_BY_DAY
WHERE DATE_KEY BETWEEN STARTPERIOD AND ENDPERIOD
group by CONSUMER_KEY,SERVICE_KEY,DECODE (to_number(to_char(to_date(DATE_KEY,'YYYYMMDD'),'D')),6,0,7,0,1)                                                                                             
ORDER BY CONSUMER_KEY,SERVICE_KEY,DECODE (to_number(to_char(to_date(DATE_KEY,'YYYYMMDD'),'D')),6,0,7,0,1)                                                                                             
GROUP BY CONSUMER_KEY,POW_KEY
WHERE RNO=1;3rd one
INSERT INTO WASTE_PREF_TOD
        (PERIOD_KEY,
        CONSUMER_KEY,
        PREFTOD,
        FIN_SCOR_TOD,
        GRANULAR
SELECT STARTPERIOD PERIOD_KEY,CONSUMER_KEY,TOD_KEY  PREFTOD,nvl(FIN_SCOR_TOD,-1),GRANULAR1 GRANULAR FROM
SELECT CONSUMER_KEY,TOD_KEY,FIN_SCOR_TOD,
ROW_NUMBER() OVER ( PARTITION BY CONSUMER_KEY ORDER BY FIN_SCOR_TOD DESC,TOD_KEY ) RNO
FROM
SELECT CONSUMER_KEY,TOD_KEY,SUM(SCORE_SERVICE_WEIGHT) FIN_SCOR_TOD FROM
SELECT TOD_KEY,CONSUMER_KEY,SERVICE_KEY,DUR,TRAN,VOLU,TOT_DUR,CUM_DUR,TOT_TRAN,CUM_TRAN,TOT_VOL,CUM_VOL,SCORE_DUR,SCORE_TRAN,SCORE_VOL,
1*NVL(SCORE_DUR,0)+1*NVL(SCORE_TRAN,0)+1*NVL(SCORE_VOL,0) TOT_SCOR ,
CASE
WHEN SERVICE_KEY= 0 THEN
1*SCORE_DUR
WHEN SERVICE_KEY IN ('1','3') THEN
1*SCORE_TRAN
WHEN SERVICE_KEY  = 2 THEN
1*SCORE_VOL
END SCORE_SERVICE_WEIGHT FROM
select TOD_KEY,consumer_key,service_key,sumDUR dur,SUMTRAN tran,sumVOL volu,
tot_dur,cum_dur,tot_tran,cum_tran,tot_vol,cum_vol,
case
when tot_dur > 0 then
cum_dur*100/tot_dur
end score_dur,
case
when tot_tran > 0 then
cum_tran*100/tot_tran
end score_tran,
case
when tot_vol > 0 then
cum_vol*100/tot_vol
end  score_vol
from
SELECT CONSUMER_KEY,SERVICE_KEY,TOD_KEY,SUMDUR,SUMTRAN,SUMVOL,SUM(SUMDUR) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ) TOT_DUR,
SUM(SUMDUR) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ORDER BY SUMDUR,TOD_KEY) CUM_DUR,
--SUM(SUMDUR) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ORDER BY SUMDUR,DOW_KEY,RNO) CUM_DUR,
SUM(SUMTRAN) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ) TOT_TRAN,
SUM(SUMTRAN) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ORDER BY SUMTRAN,TOD_KEY) CUM_TRAN,
--SUM(SUMDUR) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ORDER BY SUMDUR,DOW_KEY,RNO) CUM_DUR,
SUM(SUMVOL) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ) TOT_VOL,
SUM(SUMVOL) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ORDER BY SUMVOL,TOD_KEY) CUM_VOL
--SUM(SUMDUR) OVER (PARTITION BY CONSUMER_KEY,SERVICE_KEY ORDER BY SUMDUR,DOW_KEY,RNO) CUM_DUR,
FROM
SELECT CONSUMER_KEY,SERVICE_KEY,TOD_KEY,
sum(SUM_OF_DURATION) sumdur,SUM(NO_OF_TRANSACTIONS) sumtran,sum(SUM_OF_VOLUME) sumvol
--ROW_NUMBER () OVER (ORDER BY CONSUMER_KEY) RNO
FROM SERVICE_FACTS_BY_DAY
WHERE DATE_KEY BETWEEN STARTPERIOD AND ENDPERIOD
group by CONSUMER_KEY,SERVICE_KEY,TOD_KEY
ORDER BY CONSUMER_KEY,SERVICE_KEY,TOD_KEY
GROUP BY CONSUMER_KEY,TOD_KEY
WHERE RNO=1;

Might be like this (don't like the distinct operator)
with
all_sums as
(select consumer_key,
        service_key,
        'd_' || to_char(date_key,'yyyymmdd','d') d_key,
        sum(sum_of_duration) over (partition by consumer_key,service_key,'d_' || to_char(date_key,'yyyymmdd','d') order by null) d_sumdur,
        sum(no_of_transactions) over (partition by consumer_key,service_key,'d_' || to_char(date_key,'yyyymmdd','d') order by null) d_sumtran,
        sum(sum_of_volume) over (partition by consumer_key,service_key,'d_' || to_char(date_key,'yyyymmdd','d') order by null) d_sumvol,
        'p_' || decode(to_char(date_key,'yyyymmdd','d'),'6','0','7','0','1') p_key,
        sum(sum_of_duration) over (partition by consumer_key,service_key,'p_' || decode(to_char(date_key,'yyyymmdd','d'),'6','0','7','0','1')
                                       order by null) p_sumdur,
        sum(no_of_transactions) over (partition by consumer_key,service_key,'p_' || decode(to_char(date_key,'yyyymmdd','d'),'6','0','7','0','1')
                                          order by null) p_sumtran,
        sum(sum_of_volume) over (partition by consumer_key,service_key,'p_' || decode(to_char(date_key,'yyyymmdd','d'),'6','0','7','0','1'),
                                     order by null) p_sumvol,
        't_' || tod_key t_key,
        sum(sum_of_duration) over (partition by consumer_key,service_key,'t_' || tod_key order by null) t_sumdur,
        sum(no_of_transactions) over (partition by consumer_key,service_key,'t_' || tod_key order by null) t_sumtran,
        sum(sum_of_volume) over (partition by consumer_key,service_key,'t_' || tod_key order by null) t_sumvol,
   from service_facts_by_day
  where date_key between startperiod and endperiod
all_queries as
(select distinct consumer_key,service_key,the_key,sumdur,sumtrans,sumvol
   from (select consumer_key,service_key,d_key the_key,d_sumdur sumdur,d_sumtrans sumtrans,d_sumvol sumvol
           from all_sums
         union all
         select consumer_key,service_key,p_key,p_sumdur,p_sumtrans,p_sumvol
           from all_sums
         union all
         select consumer_key,service_key,t_key,t_sumdur,t_sumtrans,t_sumvol
           from all_sums
select startperiod,consumer_key,the_key,nvl(fin_scor_type,-1),granular1
  from (select consumer_key,
               the_key,
               fin_scor_type,
               row_number() over (partition by consumer_key,the_key order by fin_scor_type desc,the_key) rno
          from (select consumer_key,the_key,sum(score_service_weight) fin_scor_type,the_key
                  from (select tod_key,consumer_key,service_key,the_key,
                               case when service_key = 0
                                    then score_dur
                                    when service_key in (1,3)
                                    then score_tran
                                    when service_key = 2
                                    then score_vol
                               end score_service_weight
                          from (select tod_key,consumer_key,service_key,the_key,
                                       case when tot_dur > 0
                                            then kum_dur * 100 / tot_dur
                                       end score_dur,
                                       case when tot_tran > 0
                                            then kum_tran * 100 / tot_tran
                                       end score_tran,
                                       case when tot_vol > 0
                                            then kum_vol * 100 / tot_vol
                                       end score_vol
                                  from (select consumer_key,service_key,key_type,the_key,
                                               sum(sumdur) over (partition by consumer_key,service_key,the_key) tot_dur,
                                               sum(sumdur) over (partition by consumer_key,service_key,the_key order by sumdur,the_key) kum_dur,
                                               sum(sumtran) over (partition by consumer_key,service_key,the_key) tot_tran,
                                               sum(sumtran) over (partition by consumer_key,service_key,the_key order by sumtran,the_key) kum_tran,
                                               sum(sumvol) over (partition by consumer_key,service_key,the_key) tot_vol,
                                               sum(sumvol) over (partition by consumer_key,service_key,the_key order by sumvol,the_key) kum_vol
                                          from (select consumer_key,service_key,the_key,sumdur,sumtran,sumvol
                                                  from all_queries
                                                 group by consumer_key,service_key,the_key
                 group by consumer_key,the_key
where rno = 1Regards
Etbin
Edited by: Etbin on 6.6.2010 2:17
got rid of distinct
with
all_sums as
(select consumer_key,
        service_key,
        'd_' || to_char(date_key,'yyyymmdd','d') d_key,
        sum(sum_of_duration) over (partition by consumer_key,service_key,'d_' || to_char(date_key,'yyyymmdd','d') order by null) d_sumdur,
        sum(no_of_transactions) over (partition by consumer_key,service_key,'d_' || to_char(date_key,'yyyymmdd','d') order by null) d_sumtran,
        sum(sum_of_volume) over (partition by consumer_key,service_key,'d_' || to_char(date_key,'yyyymmdd','d') order by null) d_sumvol,
        'p_' || decode(to_char(date_key,'yyyymmdd','d'),'6','0','7','0','1') p_key,
        sum(sum_of_duration) over (partition by consumer_key,service_key,'p_' || decode(to_char(date_key,'yyyymmdd','d'),'6','0','7','0','1')
                                       order by null) p_sumdur,
        sum(no_of_transactions) over (partition by consumer_key,service_key,'p_' || decode(to_char(date_key,'yyyymmdd','d'),'6','0','7','0','1')
                                          order by null) p_sumtran,
        sum(sum_of_volume) over (partition by consumer_key,service_key,'p_' || decode(to_char(date_key,'yyyymmdd','d'),'6','0','7','0','1'),
                                     order by null) p_sumvol,
        't_' || tod_key t_key,
        sum(sum_of_duration) over (partition by consumer_key,service_key,'t_' || tod_key order by null) t_sumdur,
        sum(no_of_transactions) over (partition by consumer_key,service_key,'t_' || tod_key order by null) t_sumtran,
        sum(sum_of_volume) over (partition by consumer_key,service_key,'t_' || tod_key order by null) t_sumvol,
        row_number() over (partition by consumer_key,service_key) the_row
   from service_facts_by_day
  where date_key between startperiod and endperiod
all_queries as
(select consumer_key,service_key,d_key the_key,d_sumdur sumdur,d_sumtrans sumtrans,d_sumvol sumvol
   from all_sums
  where the_row = 1
union all
select consumer_key,service_key,p_key,p_sumdur,p_sumtrans,p_sumvol
   from all_sums
  where the_row = 1
union all
select consumer_key,service_key,t_key,t_sumdur,t_sumtrans,t_sumvol
   from all_sums
  where the_row = 1
select startperiod,consumer_key,the_key,nvl(fin_scor_type,-1),granular1
  from (select consumer_key,
               the_key,
               fin_scor_type,
               row_number() over (partition by consumer_key,the_key order by fin_scor_type desc,the_key) rno
          from (select consumer_key,the_key,sum(score_service_weight) fin_scor_type,the_key
                  from (select tod_key,consumer_key,service_key,the_key,
                               case when service_key = 0
                                    then score_dur
                                    when service_key in (1,3)
                                    then score_tran
                                    when service_key = 2
                                    then score_vol
                               end score_service_weight
                          from (select tod_key,consumer_key,service_key,the_key,
                                       case when tot_dur > 0
                                            then kum_dur * 100 / tot_dur
                                       end score_dur,
                                       case when tot_tran > 0
                                            then kum_tran * 100 / tot_tran
                                       end score_tran,
                                       case when tot_vol > 0
                                            then kum_vol * 100 / tot_vol
                                       end score_vol
                                  from (select consumer_key,service_key,key_type,the_key,
                                               sum(sumdur) over (partition by consumer_key,service_key,the_key) tot_dur,
                                               sum(sumdur) over (partition by consumer_key,service_key,the_key order by sumdur,the_key) kum_dur,
                                               sum(sumtran) over (partition by consumer_key,service_key,the_key) tot_tran,
                                               sum(sumtran) over (partition by consumer_key,service_key,the_key order by sumtran,the_key) kum_tran,
                                               sum(sumvol) over (partition by consumer_key,service_key,the_key) tot_vol,
                                               sum(sumvol) over (partition by consumer_key,service_key,the_key order by sumvol,the_key) kum_vol
                                          from (select consumer_key,service_key,the_key,sumdur,sumtran,sumvol
                                                  from all_queries
                                                 group by consumer_key,service_key,the_key
                 group by consumer_key,the_key
where rno = 1

Similar Messages

  • Need to re write as a one query

    Hi,
    I have a below two queries and i need re write as same query.I'm passing test session id's to second query as of now.In second query i have minimum 5 recods for 1 test session id.finally I'm converting rows as a column from second query based on roster_domain_name column(see the finally o/p).could you some on help.advance thanks.
    1st query
    SELECT DISTINCT a.test_session_id test_session_id, address,
                    TO_CHAR (birth_date, 'yyyy-MM-dd') AS birth_date,
                    branching_profile_name, city, email, exnum, first_name,
                    home_phone, institution_id_display, last_name, middle_name,
                    site_id_display, state_name, student_id,
                    TO_CHAR (test_session_date,
                             'yyyy-MM-dd') AS test_session_date, zip
               FROM vuestudenttestsessioninfo a, test_session_detail b
              WHERE EXISTS (
                       SELECT td.test_detail_id
                         FROM test_detail td
                        WHERE domain_map_id IS NOT NULL
                          AND b.test_detail_id = td.test_detail_id
                          AND domain_map_id IN (27604,27605,27606,27607))
                AND site_id IN ('8904')
               AND TRUNC (test_session_date) BETWEEN TO_DATE ('11/24/2009',
                                                               'MM/DD/YYYY'
                                                  AND TO_DATE ('12/4/2009',
                                                               'MM/DD/YYYY'
                AND a.test_session_status_id IN (3, 4)
                AND a.test_session_id = b.test_session_id
           ORDER BY address1st query o/p like below
    TEST_SESSION_ID     ADDRESS     BIRTH_DATE     BRANCHING_PROFILE_NAME     CITY     EMAIL     EXNUM     FIRST_NAME     HOME_PHONE     INSTITUTION_ID_DISPLAY     LAST_NAME     MIDDLE_NAME     SITE_ID_DISPLAY     STATE_NAME     STUDENT_ID     TEST_SESSION_DATE     ZIP
    SELECT a.test_session_id,c.roster_domain_name,to_char(a.score),a.sem FROM
          test_session_detail a,test_session b ,test_detail c
          WHERE a.test_session_id = b.test_session_id
          AND c.test_detail_id = a.test_detail_id
          AND exists (
          select td.test_detail_id
          from test_detail td
          where domain_map_id is not  null
          and c.test_detail_id =td.test_detail_id
          and domain_map_id in('303','306','305','304'))
          AND b.test_session_id in (getting session ids from 1st query)
          AND domain_group_id NOT IN (
          SELECT domain_group_id
          FROM test_session_detail a,test_session b
          WHERE a.test_session_id = b.test_session_id
          AND a.domain_group_id is not null
          AND b.test_session_status_id = 4
          AND a.test_session_status_id <> 3
          AND b.test_session_id IN (getting session ids from 1st query))
    2nd query o/p
    TEST_SESSION_ID     ROSTER_DOMAIN_NAME     TO_CHAR(A.SCORE)     SEM
    final o/p
    Address     Birth Date     Branching Profile     City     Email     Exnum     First Name     Home Phone     Inst ID     Last Name     Middle Initial     Site ID     State/ Province     Student ID     Test Date     Zip Code     AR - Integers and Fractions     AR - Decimal Numbers     AR - Percent     AR - Estim, Ordering, Numb. Sense     AR - Word Problems

    Hi ,
    Version *10.1.0.2.0*
    Business rule is:
    I have two scenarios 1) can use first query getting result
    2) can use both queries getting result.
    In second scenario i'm facing problem with regarding taking more time due to executing two queries one after one.
    because i'm getting test session id's from first query executing and displaying results from both quires .Now i have thought to merge both queries as a one query.I think it's possible with in line view quires(2nd query).Pls help
    And DDL part i'm using 1 view and reaming tables.here those scripts.
    VIEW vuestudenttestsessioninfo
    Name                                      Null?    Type                       
    STUDENT_ID                                NOT NULL VARCHAR2(50)               
    FIRST_NAME                                NOT NULL VARCHAR2(50)               
    MIDDLE_NAME                                        VARCHAR2(50)               
    LAST_NAME                                 NOT NULL VARCHAR2(50)               
    ADDRESS                                            VARCHAR2(201)              
    CITY                                               VARCHAR2(30)               
    STATE_PROVINCE_COUNTRY                             VARCHAR2(30)               
    ZIP                                                VARCHAR2(20)               
    EMAIL                                              VARCHAR2(100)              
    HOME_PHONE                                         VARCHAR2(20)               
    CELL_PHONE                                         VARCHAR2(20)               
    BIRTH_DATE                                         DATE                       
    STUDENT_ID_PK                             NOT NULL NUMBER                     
    EXNUM                                     NOT NULL NUMBER(9,)                 
    TEST_SESSION_DATE                                  DATE                       
    COMPLETION_DATE                                    DATE                       
    TEST_SESSION_ID                           NOT NULL NUMBER(9,)                 
    INSTITUTION_ID                            NOT NULL NUMBER                     
    SITE_ID                                   NOT NULL NUMBER                     
    BRANCHING_PROFILE_ID                      NOT NULL NUMBER(10,)                
    TEST_SESSION_STATUS_ID                    NOT NULL NUMBER(10,)                
    INSTITUTION_ID_DISPLAY                             VARCHAR2(10)               
    SITE_ID_DISPLAY                                    VARCHAR2(10)               
    STATE_NAME                                         VARCHAR2(30)               
    BRANCHING_PROFILE_NAME                             VARCHAR2(100)              
    SITE_NAME                                 NOT NULL VARCHAR2(200)              
    ADDRESS_2                                          VARCHAR2(100)              
    ADDRESS_1                                          VARCHAR2(100)
    SQL> desc test_session  
    Name                                      Null?    Type
    TEST_SESSION_ID                           NOT NULL NUMBER(9)
    INSTITUTION_ID                            NOT NULL NUMBER
    STUDENT_ID_PK                             NOT NULL NUMBER(9)
    BRANCHING_PROFILE_ID                      NOT NULL NUMBER(10)
    TEST_SESSION_STATUS_ID                    NOT NULL NUMBER(10)
    TEST_SESSION_DATE                                  DATE
    ACCESSED_TIMES                                     NUMBER(9)
    COMPLETION_DATE                                    DATE
    DURATION                                           NUMBER(10)
    CREATED_ON                                         DATE
    MODIFIED_ON                                        DATE
    CREATED_BY                                         NUMBER
    MODIFIED_BY                                        NUMBER
    IS_RESUMED                                         CHAR(1)
    SQL> desc test_session_detail
    Name                                      Null?    Type
    TEST_SESSION_DETAIL_ID                    NOT NULL NUMBER(9)
    TEST_SESSION_ID                           NOT NULL NUMBER(9)
    TEST_DETAIL_ID                            NOT NULL NUMBER(10)
    TEST_SESSION_STATUS_ID                             NUMBER
    THETA                                              NUMBER
    SCORE                                              NUMBER
    PERCENTILE                                         NUMBER
    SEM                                                NUMBER
    TEST_START_DATE                                    DATE
    TEST_END_DATE                                      DATE
    TEST_DURATION                                      NUMBER
    CREATED_ON                                         DATE
    MODIFIED_ON                                        DATE
    CREATED_BY                                         NUMBER
    MODIFIED_BY                                        NUMBER
    TEST_SEED                                          VARCHAR2(15)
    TEST_ALIAS                                         VARCHAR2(30)
    COMPANION_FORM                                     CHAR(1)
    DURATION_START_DATE                                TIMESTAMP(6)
    DURATION_END_DATE                                  TIMESTAMP(6)
    DOMAIN_GROUP_ID                                    NUMBER
    TIMER_LIMIT                                        VARCHAR2(100)
    SQL> desc test_detail
    Name                                      Null?    Type
    TEST_DETAIL_ID                            NOT NULL NUMBER(10)
    TEST_TYPE_ID                              NOT NULL NUMBER(10)
    OPERATIONAL_POOL_ID                                NUMBER(10)
    FIELD_TEST_POOL_ID                                 NUMBER(10)
    INSTITUTION_ID                            NOT NULL NUMBER
    TEST_NAME                                 NOT NULL VARCHAR2(500)
    TEST_ALIAS                                         VARCHAR2(30)
    DESCRIPTION                                        VARCHAR2(100)
    OPERATIONAL_TEST_LENGTH                            NUMBER
    ACTIVE_STATUS                                      CHAR(1)
    DELETE_STATUS                                      CHAR(1)
    FIELD_TEST_ITEM                                    VARCHAR2(1)
    FIELD_TEST_LENGTH                                  NUMBER
    IS_DIR_SAMPLE                                      CHAR(1)
    DIR_SAMPLE_PATH                                    VARCHAR2(1000)
    CREATED_ON                                         DATE
    MODIFIED_ON                                        DATE
    CREATED_BY                                         NUMBER
    MODIFIED_BY                                        NUMBER
    FORM_NAME                                          VARCHAR2(10)
    DOMAIN_MAP_ID                                      NUMBER(9)
    DOMAIN_SEQUENCE                                    NUMBER(9)
    ROSTER_DOMAIN_NAME                                 VARCHAR2(100)

  • Merging  3 select in one query

    Good Day!!!
    Got a little problem guys,
    i got 3 tables and i need to get get the count of plate_no on each table but all table have where condition im using oracle xe 11g
    here is my 3 query:
    SELECT COUNT(PLATE_NO)
    FROM EX_DEPOT
    WHERE PLANT_ORIGIN IN ('Batangas','Teresa','Bulacan')
    AND STATUS IN ('ON THE WAY TO PLANT','TRUCK IS LOADED','FOR QUEUING','QUEUING FOR DEPOT','ON THE WAY TO DEPOT'
    ,'ON THE WAY TO DEPOT','UNLOADING FOR DEPOT')
    SELECT COUNT(PLATE_NO)
    FROM EX_BULACAN
    WHERE status not in ('NA as this moment','SERVED','CANCELLED')
    AND PLANT_ORIGIN IN ('Batangas','Teresa','Bulacan','Norzagaray')
    select count(PLATE_NO)
    from BREAK
    WHERE LOCATION NOT IN ('NA AT THIS MOMENT');Note: Is that possible to make that 3 query to one?
    please help need that for my reports
    Regards,
    Mike

    >
    Is that possible to make that 3 query to one?
    >
    Since the data sources have nothing in common just UNION ALL the results together
    SELECT 'EX_DEPOT' data_source, COUNT(PLATE_NO) PLATE_COUNT
    FROM EX_DEPOT
    WHERE PLANT_ORIGIN IN ('Batangas','Teresa','Bulacan')
    AND STATUS IN ('ON THE WAY TO PLANT','TRUCK IS LOADED','FOR QUEUING','QUEUING FOR DEPOT','ON THE WAY TO DEPOT'
    ,'ON THE WAY TO DEPOT','UNLOADING FOR DEPOT')
    UNION ALL
    SELECT 'EX_BULACAN', COUNT(PLATE_NO)
    FROM EX_BULACAN
    WHERE status not in ('NA as this moment','SERVED','CANCELLED')
    AND PLANT_ORIGIN IN ('Batangas','Teresa','Bulacan','Norzagaray')
    UNION ALL
    SELECT BREAK, count(PLATE_NO)
    from BREAK
    WHERE LOCATION NOT IN ('NA AT THIS MOMENT');The result will something like:
    DATA_SOURCE PLATE_COUNT
    EX_DEPOT 582
    EX_BULACAN 74
    BREAK 103

  • Need to pull ranked item from one query into new query

    Hi,
    I have a parent query in which I assign a rank to characteristic values based on a key figure, in dollars. I need to pull the top 4 items from that parent query into 4 seperate child queries (i.e. child query 1 is written based on ranked item 1, child query 2 is written based on ranked item 2, etc.) Does anyone have any ideas how to achieve this?
    Thanks
    CM

    Hi,
    I have a parent query in which I assign a rank to characteristic values based on a key figure, in dollars. I need to pull the top 4 items from that parent query into 4 seperate child queries (i.e. child query 1 is written based on ranked item 1, child query 2 is written based on ranked item 2, etc.) Does anyone have any ideas how to achieve this?
    Thanks
    CM

  • Need to use the results of one query as an input to another query

    Hi, I have one sql query in my XML file, that returns more than one values for a column.
    and i want to use this output one by one as an input to the second query to retrive the data from the second query.
    Could please someone tell me if its possible in XML Publisher?
    If possible, please share the syntax to do the same
    For eg:
    Query 1:
    Select data1, data2 from query1 ; -- output data1 and data2
    want to use data1 and data2 one by one in the below query
    Query 2:
    select * from abc where name_id= data1/data2;
    Thanks and Regards
    Madhu

    Make sure your cursor declarations are in your declare section, not between the begin and end statements.

  • I have two accounts and need to merge into one account. How? Where to even ask this question? Chat will not assist in this.

    Over the years I accidentally opened a second Adobe account, both with product registrations. I need to merge these accounts into one and see no way to do that. Updates to software will not install because serial for previous version not found on upgrade versions now installed. Could the 2 different accounts be a cause for this?  I got no help at all from chat.

    Adobe chat support is likely to be the only resource capable of dealing with your account.
    Chat support - For the link below click the Still Need Help? option in the blue area at the bottom and choose the chat option...
    Adobe ID and registration chat support (non-CC)
    http://helpx.adobe.com/x-productkb/global/service-c1.html ( http://adobe.ly/19r6ZDp )

  • Grouped and non-grouped SELECT in one query: help!

    look first at: Wrong result when I use CASE on this forum. Here I wanted to get the user who created and the user who solved a problem (Lets call it Validation Error from now on (VE)).
    The thing is: I already have a query who returns me lots of information about a VE.
    The query in the previous thread returned me additional info about that VE (that is the creating_user and the solving_user). The 1st query is no group select, but the second is! Still, I need to combine those two in one query.
    1st query:
    select ve.seq,
         max((case vah.action when 'C' then vah.ur_code else null end)) created,
         max((case vah.action when 'S' then vah.ur_code else null end)) solved
    from validation_errors ve
    left outer join ver_action_histories vah
    on (ve.seq = vah.ver_seq AND ve.log_date = vah.ver_log_date)
    where ve.seq = 12860687
    group by ve.seq;Result:
    seq       | created | solved
    12860687    Bob       Bobdont mind the "where"-clause, it is just to make the query go faster
    what I do is: I join the VE with the ver_action_histories table which contains the users and what action they performed on a VE.
    Now I just want to add that information to the results of an other query which also returns lots of information about a VE.
    2nd query:
    select ve.seq "VE seq", mh.seq "Counter seq",
              ve.log_date, ve.solve_date, ve.solved Status, ve.failure_code, ve.mde_code,
              mh.meter_type,
              iv.mr_type, iv.mr_reason,
              ih.mmr_seq
    from validation_errors ve
    inner join meter_histories mh
    on (ve.mhy_seq = mh.seq)
    left outer join index_values iv
    on (ve.mhy_seq = iv.mhy_seq AND ve.log_date =iv.timestamp)
    left outer join index_histories ih
    on (ve.mhy_seq = ih.ive_mhy_seq)
    where ve.seq = 8653936
    and sysdate >= mh.start_date
    and sysdate < mh.end_date;dont mind the "where" and "and"-clauses ... I hope the result of this query will simplify things ...
    Result:
    seq        |   counter seq | log_date | solved_date | status    | failure_code | ...
    12860687       4568          1-jan-06   2-jan-06      Solved      ABCNow the actual question: Is it possible to combine those queries in one query? I just want the results of the first query (creating_user and solving_user) to be added as columns to the second result. Performance is very important. Please tell me that its possible?
    Wanted Result:
    seq        |   counter seq | log_date | solved_date | status    | failure_code | created  | solved  | ...
    12860687       4568          1-jan-06   2-jan-06      Solved      ABC            Bob        BobIf anything I explained is unclear, please tell so I can try to explain it in an easier way.

    Try an in line view:
    select *
    from
    ( <your first query goes here > ) a
    , ( <your second query goes here > ) b
    where a.seq = b.seq

  • Need to merge the query's

    Hi,
    Ii need to merge the below 2 queries.could you please help some one.
    primary foreign key relation of major_id column
    major.major_id primary key.
    major_inactive_list.major_id referential integrity
    SELECT   m.major_inactive_id, m.institution_id, m.major_id, m.created_on,
             m.modified_on, m.created_by, m.modified_by, m.active_status
        FROM major_inactive_list m
       WHERE m.institution_id IN (1, 5)
    ORDER BY m.institution_id
    SELECT   M.major_id ,
                     M.major_name ,
                     M.major_code ,
                     M.major_comment,
                     M.delete_status,
                     M.active_status,
                     M.institution_id,
                     M.default_major
                FROM major M
               WHERE     (M.institution_id IN (1, 5, 6))
                     AND M.delete_status = '0'
                     AND M.active_status = '1'
                     AND (M.major_id NOT IN (768002, 767978))
                  OR     M.institution_id = 6
                     AND M.active_status = '0'
                     AND M.delete_status = '0'
            ORDER BY M.institution_id DESC, UPPER (M.major_name)

    need to re write as a single query instead of 2 queries.There should be some logic behind making it as a single query. I was looking for you to explain that. If you ask me to make it a single query without giving any details i would do this.
    with t1
    as
    SELECT m.major_inactive_id, m.institution_id, m.major_id, m.created_on,
           m.modified_on, m.created_by, m.modified_by, m.active_status
      FROM major_inactive_list m
    WHERE m.institution_id IN (1, 5)
    t2 as
    SELECT M.major_id ,
           M.major_name ,
           M.major_code ,
           M.major_comment,
           M.delete_status,
           M.active_status,
           M.institution_id,
           M.default_major
      FROM major M
    WHERE M.institution_id IN (1, 5, 6)
       AND M.delete_status = '0'
       AND M.active_status = '1'
       AND M.major_id NOT IN (768002, 767978)
        OR M.institution_id = 6
       AND M.active_status = '0'
       AND M.delete_status = '0'
    select t1.*, t2.*
      from t1, t2
    where t1.major_id = t2.major_id

  • I need to print one query result as a single row

    Hi,
    I need to print one query result as a single row ,which gives more than one value (of subinventories)and also i would like to print the quantity of that particular subinventory at particular place.Please suggest how can i do this in the report builder?

    Actually I need to print inventory report with subinventory break up.For that all subinventories of category code AB are taken as single row.Based on that subinventory value Quantity must be printed at that particular place.
    For ex
    Quantity
    Item no Description Subinventory Code AB_Abc AB_Def AB_ghi
    1 ***** 12 9
    2 ****** 8 5
    like that.I am waiting for the reply.Plz its some how urgent.
    Thank you,

  • I need two query in one report (two detail section in one query)

    Hi master sorry for again distribute
    Sir I need two query in one report
    Because I need two detail section in my one report
    Such as
    Master
    Vno=9088989
    Detail          1
    =
    =
    ==
    =
    Total                     99999
    Detail          2
    =
    =
    ==
    =
    Total                     33333
    Sir how I get this type of report
    Please give me idea
    Thanking you
    Aamir

    I want to see the report as follow.
    d_name: CPU-1
    date: -----------
    Software installed:
    sw_id, software, version, serial_no, sw_type
    (list of softwares attached, can be more then one)
    Hardware attached:
    hw_id, hardware, specification (same like software list, it will contain hardware list attached to specific device),
    Please if you can help me that how will i make a query for this.
    Thanks and Regards
    Maz

  • 2 computers, 2 libraries and I need to merge into one

    I have two computers with separate libraries that I need to merge. I've created a home network and attempted to import/export with no luck. How can I merge the two libraries because my laptop is about to crash and it's my primary library. Please help!

    Adobe chat support is likely to be the only resource capable of dealing with your account.
    Chat support - For the link below click the Still Need Help? option in the blue area at the bottom and choose the chat option...
    Adobe ID and registration chat support (non-CC)
    http://helpx.adobe.com/x-productkb/global/service-c1.html ( http://adobe.ly/19r6ZDp )

  • One Query need to tune

    I have one query below to tune.
    Here one table USER_RETAILER_MAP and its column BELONGS_TO having value only 'Y' and 'N'.
    Created bitmap index but i am not getting any cost difference.
    Please share your idea ,how to tune and what process should follow.
    SQL> explain plan for
    2 SELECT a.user_id,
    3 a.user_nm,
    4 2 AS max_level
    5 FROM gss_user a
    6 WHERE a.user_id NOT IN (SELECT user_id
    7 FROM user_retailer_map
    8 WHERE retailer_id IN (SELECT b.retailer_id
    9 FROM user_retailer_map b,
    10 retailer c
    11 WHERE
    12 b.retailer_id = c.retailer_id
    13 AND b.user_id = :a
    14 AND c.status = 'ACTIVE'
    15 AND b.managed_by = 'Y')
    16 AND belongs_to = 'Y')
    17 AND Upper(a.status) = 'ACTIVE'
    18 AND a.user_id IN (SELECT user_id
    19 FROM user_hierarchy
    20 WHERE parent_user_id = :b)
    21 AND a.gmac_dealer_user_flg = 'D'
    22 ORDER BY Upper(user_nm) ASC
    23 ;
    Explained.
    SQL> @utlxpls
    PLAN_TABLE_OUTPUT
    | Id | Operation | Name | Rows | Bytes | Cost |
    | 0 | SELECT STATEMENT | | 1 | 91 | 65 |
    | 1 | SORT ORDER BY | | 1 | 91 | 65 |
    |* 2 | HASH JOIN ANTI | | 1 | 91 | 63 |
    | 3 | NESTED LOOPS SEMI | | 7 | 504 | 9 |
    |* 4 | TABLE ACCESS FULL | GSS_USER | 33 | 1254 | 9 |
    |* 5 | INDEX UNIQUE SCAN | XPKGSS_USER_HIERARCHY | 7 | 238 | |
    | 6 | VIEW | VW_NSO_1 | 212 | 4028 | 53 |
    |* 7 | HASH JOIN | | 212 | 15476 | 53 |
    |* 8 | HASH JOIN | | 15 | 675 | 9 |
    | 9 | TABLE ACCESS BY INDEX ROWID| USER_RETAILER_MAP | 15 | 420 | 4 |
    |* 10 | INDEX RANGE SCAN | INDX_USERID_MNGBY | 15 | | 1 |
    |* 11 | INDEX FAST FULL SCAN | INDX_RETAILE | 1594 | 27098 | 4 |
    |* 12 | TABLE ACCESS FULL | USER_RETAILER_MAP | 22885 | 625K| 43 |
    Predicate Information (identified by operation id):
    2 - access("A"."USER_ID"="VW_NSO_1"."$nso_col_1")
    4 - filter(UPPER("A"."STATUS")='ACTIVE' AND "A"."GMAC_DEALER_USER_FLG"='D')
    5 - access("A"."USER_ID"="USER_HIERARCHY"."USER_ID" AND "USER_HIERARCHY"."PARENT_USER
    _ID"=:Z)
    7 - access("USER_RETAILER_MAP"."RETAILER_ID"="B"."RETAILER_ID")
    8 - access("B"."RETAILER_ID"="C"."RETAILER_ID")
    10 - access("B"."USER_ID"=:Z AND "B"."MANAGED_BY"='Y')
    11 - filter("C"."STATUS"='ACTIVE')
    12 - filter("USER_RETAILER_MAP"."BELONGS_TO"='Y')
    }

    How to post a SQL statement tuning request...
    HOW TO: Post a SQL statement tuning request - template posting

  • Need to merge xml o/p from different sources to generate BIP Report from OA page

    Hi,
    Currently in our product Quoting , we are using many VO queries to generate the Report
    Now we have created one data template file to combine all VO queries to generate xml o/p
    The problem we are facing is that we didn't added Contracts VO query in our DT file so we need to merge
    xml o/p coming from DT file and Contracts VO and pass to Process Template XDO api to generate the report
    Please tell how to merge the xml o/p in OAF ?

    Thanks Shridhar for reply ,  you provided code for xml coming from two VO
    but I am having scenario where getting one xml o/p from data template file and seconf xml o/p getting from contracts api as -
    ByteArrayOutputStream l_docXML = new ByteArrayOutputStream(1024);
    // Here getting xml o/p from DT file
    l_docXML = (ByteArrayOutputStream)this.getDataTemplateXML(transaction,"ASO","ASOPD",parameters1,null);
    // Here getting xml o/p from contacts api
    ContractTermsXMLGenerator.writeXML(PrintQuote,
                        (OutputStream) l_conXML,
       true,
       documentType,
       new Number(params[8]),
       new Number("0"));
    // code to merge two xml into one xml m_docXML
    try{
                 if (l_conXML.size() > 0)
                      DOMParser dp = new DOMParser();
                      l_docIP = new ByteArrayInputStream(l_docXML.toByteArray()); 
                      dp.parse(l_docIP);
                      XMLDocument xDoc = dp.getDocument();
                      l_conIP = new ByteArrayInputStream(l_conXML.toByteArray());
                      dp.parse(l_conIP);
       XMLDocument cDoc = dp.getDocument();
       Node cNode = cDoc.getDocumentElement();
                      if (cNode != null)
                           Node xDocConNode = xDoc.adoptNode(cNode);
                           Node conData = xDoc.createElement("CONTRACT_DATA");
                           conData.appendChild(xDocConNode);
                           xDoc.getDocumentElement().appendChild(conData);
                         xDoc.print(m_docXML);
                         writeLog("GenerateCLMDoc::XMLMerge Complete");
               catch(Exception e)
           writeLog("GenerateCLMDoc:: Doc contract XML Merge - " + e.getMessage());
                      throw e;
        finally{
                        l_docIP.close();
                        l_conIP.close();
    Please check if it is correct code , do I need to change it with code provided by you
    can we chat over any messenger ?
    once again thanks for your reply

  • Need to merge the below two rows

    Hi,
    I have a sample data as shown below:
    ID     OBJID     ACT_CODE     ADDNL_INFO     ENTRY_TIME
    2523540     333003736     900     from WIP default to Queue PSD1.     1/3/2012 15:07
    2523540     333003271     100     100 from Queue PSD1 to WIP For assigment. 1/3/2012 15:43
    2523540     333003744     900     900 from WIP default to Queue PSD1.     1/3/2012 15:49
    2523540     333004966     100     100 from Queue PSD1 to WIP For assigment.     1/3/2012 16:04
    I need to merge the first two rows and get a single record for each "from" and "to" as shown below (desired output)
    ID_NUMBER     ADDNL_INFO     ENTRY_TIME     EXIT_TIME     TOTAL TIME
    2523540     PSD1     1/3/2012 15:07     1/3/2012 15:43     0.025069444
    2523540     PSD1     1/3/2012 15:49     1/3/2012 16:04     0.010231481
    I have used function on the addnl_info column to display only the name of the queue "PSD1"
    (SUBSTR(ADDNL_INFO, INSTR(ADDNL_INFO, 'PSD1'), LENGTH('PSD1'))) QUEUE_NAME
    Can any one help me out in getting the desired output.

    Below is a solution to your query:
    drop table test_Table;
    create table test_Table
      ID          number,
      objid       number,
      act_code    number,
      addl_info   varchar2(500),
      entry_time  timestamp
    insert into test_Table values (2523540, 333003736, 900, 'from WIP default to Queue PSD1.', to_timestamp('1/3/2012 15:07', 'DD/MM/YYYY HH24:MI'));
    insert into test_Table values (2523540, 333003271, 100, 'from Queue PSD1 to WIP For assigment.', to_timestamp('1/3/2012 15:43', 'DD/MM/YYYY HH24:MI'));
    insert into test_Table values (2523540, 333003744, 900, 'from WIP default to Queue PSD1.', to_timestamp('1/3/2012 15:49', 'DD/MM/YYYY HH24:MI'));
    insert into test_Table values (2523540, 333004966, 100, 'from Queue PSD1 to WIP For assigment.', to_timestamp('1/3/2012 16:04', 'DD/MM/YYYY HH24:MI'));
    select * from test_table;
    select id, addl_info, entry_time, exit_time, total_time
    from
    select a.id, a.objid, 'PSD1' addl_info, a.entry_time, lead(a.entry_time, 1, null) over (order by a.entry_time) exit_time,
           lead(a.entry_time, 1, null) over (order by a.entry_time) - a.entry_time total_time, DECODE(a.act_code, 900, 'D', 'ND') disp
      from test_Table a
    where a.id = 2523540
    where disp = 'D';
    ID             ADDL_INFO            ENTRY_TIME          EXIT_TIME                     TOTAL_TIME
    2523540     PSD1     01-MAR-12 03.07.00.000000000 PM     01-MAR-12 03.43.00.000000000 PM     0 0:36:0.0
    2523540     PSD1     01-MAR-12 03.49.00.000000000 PM     01-MAR-12 04.04.00.000000000 PM     0 0:15:0.0I see a shortcoming in the design:
    1. For "WIP default to Queue PSD1" there are two records, both containing different OBJID but same ID, which in ideal case should not happen. You MUST have a COMPOSITE key on ID and OBJID; This shall help you to identify the distinct records.
    My solution is not perfect as it is based on the ENTRY TIME. The reason being SIMPLE Ordering by the OBJID would not lead to a correct difference in the Transaction Time (referred by you as TOTAL_TIME.); Hence, for this reason I had to use ENTRY_TIME to correctly get the total_time.
    If you wish you may follow the solution else I shall always recommend to change the Table Design and follow the correct approach.
    If you are changing the Table design then following shall be a solution:
    select id, addl_info, entry_time, exit_time, total_time
    from
    select a.id, a.objid, 'PSD1' addl_info, a.entry_time, lead(a.entry_time, 1, null) over (order by a.id, a.objid) exit_time,
           lead(a.entry_time, 1, null) over (order by a.entry_time) - a.entry_time total_time, DECODE(a.act_code, 900, 'D', 'ND') disp
      from test_Table a
    where disp = 'D';Regards,
    P.

  • Can you check for data in one table or another but not both in one query?

    I have a situation where I need to link two tables together but the data may be in another (archive) table or different records are in both but I want the latest record from either table:
    ACCOUNT
    AccountID     Name   
    123               John Doe
    124               Jane Donaldson           
    125               Harold Douglas    
    MARKETER_ACCOUNT
    Key     AccountID     Marketer    StartDate     EndDate
    1001     123               10526          8/3/2008     9/27/2009
    1017     123               10987          9/28/2009     12/31/4712    (high date ~ which means currently with this marketer)
    1023     124               10541          12/03/2010     12/31/4712
    ARCHIVE
    Key     AccountID     Marketer    StartDate     EndDate
    1015     124               10526          8/3/2008     12/02/2010
    1033     125               10987         01/01/2011     01/31/2012  
    So my query needs to return the following:
    123     John Doe                        10526     8/3/2008     9/27/2009
    124     Jane Donaldson             10541     12/03/2010     12/31/4712     (this is the later of the two records for this account between archive and marketer_account tables)
    125     Harold Douglas               10987          01/01/2011     01/31/2012     (he is only in archive, so get this record)
    I'm unsure how to proceed in one query.  Note that I am reading in possibly multiple accounts at a time and returning a collection back to .net
    open CURSOR_ACCT
              select AccountID
              from
                     ACCOUNT A,
                     MARKETER_ACCOUNT M,
                     ARCHIVE R
               where A.AccountID = nvl((select max(M.EndDate) from Marketer_account M2
                                                    where M2.AccountID = A.AccountID),
                                                      (select max(R.EndDate) from Archive R2
                                                    where R2.AccountID = A.AccountID)
                   and upper(A.Name) like parameter || '%'
    <can you do a NVL like this?   probably not...   I want to be able to get the MAX record for that account off the MarketerACcount table OR the max record for that account off the Archive table, but not both>
    (parameter could be "DO", so I return all names starting with DO...)

    if I understand your description I would assume that for John Dow we would expect the second row from marketer_account  ("high date ~ which means currently with this marketer"). Here is a solution with analytic functions:
    drop table account;
    drop table marketer_account;
    drop table marketer_account_archive;
    create table account (
        id number
      , name varchar2(20)
    insert into account values (123, 'John Doe');
    insert into account values (124, 'Jane Donaldson');
    insert into account values (125, 'Harold Douglas');
    create table marketer_account (
        key number
      , AccountId number
      , MktKey number
      , FromDt date
      , ToDate date
    insert into marketer_account values (1001, 123, 10526, to_date('03.08.2008', 'dd.mm.yyyy'), to_date('27.09.2009', 'dd.mm.yyyy'));
    insert into marketer_account values (1017, 123, 10987, to_date('28.09.2009', 'dd.mm.yyyy'), to_date('31.12.4712', 'dd.mm.yyyy'));
    insert into marketer_account values (1023, 124, 10541, to_date('03.12.2010', 'dd.mm.yyyy'), to_date('31.12.4712', 'dd.mm.yyyy'));
    create table marketer_account_archive (
        key number
      , AccountId number
      , MktKey number
      , FromDt date
      , ToDate date
    insert into marketer_account_archive values (1015, 124, 10526, to_date('03.08.2008', 'dd.mm.yyyy'), to_date('02.12.2010', 'dd.mm.yyyy'));
    insert into marketer_account_archive values (1033, 125, 10987, to_date('01.01.2011', 'dd.mm.yyyy'), to_date('31.01.2012', 'dd.mm.yyyy'));
    select key, AccountId, MktKey, FromDt, ToDate
         , max(FromDt) over(partition by AccountId) max_FromDt
      from marketer_account
    union all
    select key, AccountId, MktKey, FromDt, ToDate
         , max(FromDt) over(partition by AccountId) max_FromDt
      from marketer_account_archive;
    with
    basedata as (
    select key, AccountId, MktKey, FromDt, ToDate
      from marketer_account
    union all
    select key, AccountId, MktKey, FromDt, ToDate
      from marketer_account_archive
    basedata_with_max_intervals as (
    select key, AccountId, MktKey, FromDt, ToDate
         , row_number() over(partition by AccountId order by FromDt desc) FromDt_Rank
      from basedata
    filtered_basedata as (
    select key, AccountId, MktKey, FromDt, ToDate from basedata_with_max_intervals where FromDt_Rank = 1
    select a.id
         , a.name
         , b.MktKey
         , b.FromDt
         , b.ToDate
      from account a
      join filtered_basedata b
        on (a.id = b.AccountId)
    ID NAME                     MKTKEY FROMDT     TODATE
    123 John Doe                  10987 28.09.2009 31.12.4712
    124 Jane Donaldson            10541 03.12.2010 31.12.4712
    125 Harold Douglas            10987 01.01.2011 31.01.2012
    If your tables are big it could be necessary to do the filtering (according to your condition) in an early step (the first CTE).
    Regards
    Martin

Maybe you are looking for