Order By in Sub Query

Hi All,
I am trying to following SQL
select d.deptno,
d.dname,
e.empno,
e.ename,
e.sal
from dept d,
emp e
where d.deptno = e.deptno
and (e.empno, e.sal) in ( select e2.empno, e2.sal
from emp e2
where e2.deptno = d.deptno
and rownum < 3
order by e2.sal desc)
order by d.deptno, e.sal desc
This works fine if I remove the order by clause in the subquery.
In case the order by clause is still there it give me a error
or "invalid relational operator" on the order by clause in the
subquery. WHY !!!!!!
Thanks
Monish

The version of Oracle you are using may or may not be part of
your problem. The syntax is not valid in any version.
If you are using a newer version, you can try re-writing it like
this:
SELECT   deptno, dname, empno, ename, sal
FROM     (SELECT d.deptno, d.dname,
                 e.empno, e.ename, e.sal,
                 RANK () OVER
                      (PARTITION BY d.deptno
                       ORDER BY e.sal DESC) rk
          FROM   dept d, emp e
          WHERE  d.deptno = e.deptno)
WHERE    rk < 3
ORDER BY deptno, sal DESC;
    DEPTNO DNAME               EMPNO ENAME             SAL
        10 ACCOUNTING           7839 KING             5000
        10 ACCOUNTING           7782 CLARK            2450
        20 RESEARCH             7788 SCOTT            3000
        20 RESEARCH             7902 FORD             3000
        30 SALES                7698 BLAKE            2850
        30 SALES                7499 ALLEN            1600
6 rows selected.
If you are using an older version, you can try re-writing it
like this:
SELECT  d.deptno, d.dname,
        e.empno, e.ename, e.sal
FROM    dept d, emp e
WHERE   d.deptno = e.deptno
AND     3 >
        (SELECT COUNT (*) + 1
         FROM   dept d2, emp e2
         WHERE  d2.deptno = e2.deptno
         AND    d2.deptno = d.deptno
         AND    e2.sal > e.sal)
ORDER BY d.deptno, e.sal DESC;The second solution will produce the same results as the first
and will work in newer versions as well, but will run
significantly slower on large tables.

Similar Messages

  • Order by clause in Sub query

    Hi,
    Can we use order by clause in Sub query?
    While using the order by clause, I am getting the "missing expression error" . If I remove order by clause query executing fine.
    Here is my query:
    select *
    from emp_mstr
    where emp_no in(select
    emp_no
    from emp_mstr
    order by branch_no);
    Thanks & Regards,
    Mahi

    May be you miss some required spaces also, other than wrong use of ORDER BY
    select *
    from emp_mstr
    where emp_no in
         ( select e2.emp_no
           from emp_mstr e2
    --       order by e2.branch_no
         );Why do you want to ORDER BY in the subquery, which you use with IN clause? That will not make any difference in the result..Means the result you get with ORDER BY will be same as without that.. And in this case, ORDER by is a unncessary overhead.. And Ordering is very costly..
    And why do you want to have the IN clause at all in your query? You are referring the same tables in the main query and sub query..
    The below will give the same result
    select *
    from emp_mstr
    where emp_no is not nullIf you want to use another table in the subquery, always use aliasess...
    select *
    from emp_mstr
    where emp_no in
         ( select e2.emp_no
           from emp_mstr2 e2
    --       order by e2.branch_no
         );

  • Sub query with order by

    Hi ,
    I have created a sub query with order by on a column.( i have cutomized the IKM control append to put order by).I can see the order by condition.If i use this subquery(yellow interface) in main query(is also yellow interface) i can't see the order by condition
    Subquery(Q-yellow interface):
    select
    PID,
         START_TIME,
         ACTION_TYPE_CODE
    FROM
    select      DISTINCT
         SERVICE_TRACKING_S.PID PID,
         TO_TIMESTAMP(TO_CHAR(SERVICE_TRACKING_S.ACTION_TIME,'DD-MON-YY HH24:MI:SS'),'DD-MON-YY HH24:MI:SS') START_TIME,
         SERVICE_TRACKING_S.ACTION_TYPE_CODE ACTION_TYPE_CODE
    from     KSTGDB.SERVICE_TRACKING_S SERVICE_TRACKING_S
    where          (1=1)     
    ORDER BY-----------------------------------------------
    PID
    ,START_TIME ASC
    ODI_GET_FROM
    Main query(Q1--yellow interface):
    select
    PID,
         START_TIME,
         ACTION_TYPE_CODE,
         RN,
         RN_MAX
    FROM (     
    select      
         Q.PID PID,
         Q.START_TIME START_TIME,
         CASE WHEN Q.START_TIME-LAG(Q.START_TIME,1,Q.START_TIME) OVER (PARTITION BY Q. PID ORDER BY Q.START_TIME)> numtodsinterval(75,'minute')
    or Q.PID!=LAG(Q.PID,1,0) OVER (PARTITION BY Q.PID ORDER BY Q.START_TIME) THEN 1 ELSE Q.ACTION_TYPE_CODE END ACTION_TYPE_CODE,
         ROW_NUMBER() OVER(PARTITION BY Q.PID ORDER BY Q.START_TIME) RN,
         count(*) over (PARTITION BY Q.PID ORDER BY Q.START_TIME ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING )
    RN_MAX
    from     (
    select      DISTINCT
         SERVICE_TRACKING_S.PID PID,     TO_TIMESTAMP(TO_CHAR(SERVICE_TRACKING_S.ACTION_TIME,'DD-MON-YY HH24:MI:SS'),'DD-MON-YY HH24:MI:SS') START_TIME,     SERVICE_TRACKING_S.ACTION_TYPE_CODE ACTION_TYPE_CODE
    from     KSTGDB.SERVICE_TRACKING_S SERVICE_TRACKING_S
    where     (1=1)
    ----------------- i don't see order by here--------------------------------
    ) Q
    where          (1=1)     
    ) ODI_GET_FROM
    thanks in advance
    K

    Hi,
    Add a new KM step with the SQL you want to use for the sub query and select the +"Use Current Command for Derived-Table sub-select statement"+ checkbox. This new step can be the last one of your IKM.
    Basically, you can copy the select statement of the "Insert new rows" step.
    Regards,
    JeromeFr

  • Can someone please help me with a sub query question?

    I need to list a 3rd party contract and then a list of students who belong to that contract.
    On the students segment of the listing I need to show students with student id, name, total credit hours,
    total amount spent on tuition, total amount spent on books and total amount spent on misc.
    This code has a query for the contract information and I get that just fine.
    Then it has a query that gives me total credit hours and that works fine
    then it has a query that gives me total amount spent on tuition and that works fine
    but
    when I add the next query to get total amount spent on books I get only the information for the contract, I don't get student stuff anymore.
    I would really appreciate any guidance that you could give.
    Thanks in advance, Bob Hohulski
    DECLARE
    l_conn utl_TCP.connection;
    v_filehandle utl_file.file_type;
    v_output varchar2(1000);
    v_contract_id varchar2(9);
    v_contract_addr1 varchar2(30);
    v_contract_addr2 varchar2(30);
    v_contract_city varchar2(20);
    v_contract_stat varchar2(03);
    v_contract_zip varchar2(10);
    v_contract_name varchar2(60);
    v_student_id varchar2(09);
    v_student_first_name varchar2(15);
    v_student_mid_name varchar2(15);
    v_student_last_name varchar2(60);
    v_last_out varchar2(20);
    v_student_detail_code varchar2(04);
    v_student_amount number(12,2);
    v_student_ref_number varchar2(09);
    v_credit_hrs number(7,2);
    v_tuition_amount number(12,2);
    v_books_amount number(12,2);
    v_misc_amount number(12,2);
    v_total_for_student number(12,2);
    v_current_student varchar2(09);
    v_sftregs_pidm varchar2(09);
    v_tbraccd_pidm varchar2(09);
    CURSOR c_sel_contract IS
    SELECT DISTINCT spriden_id, spriden_last_name,
    spraddr_street_line1, spraddr_street_line2,
    spraddr_city, spraddr_stat_code, spraddr_zip
    FROM spriden, spraddr
    -- WHERE spriden_id = '&Enter_Id'
    where spriden_id = 'T10474666'
    AND spriden_pidm = spraddr_pidm
    AND SPRIDEN_CHANGE_IND IS NULL;
    CURSOR c_sel_student IS
    SELECT DISTINCT spriden_id, spriden_first_name, spriden_mi, spriden_last_name,
    sftregs_credit_hr,
    tbraccd_amount,
    sftregs_pidm,
    tbraccd_pidm
    FROM spriden, tbraccd, tbbcstu, sftregs
    WHERE 559220 = tbbcstu_contract_pidm
    AND spriden_pidm = tbraccd_pidm
    AND spriden_pidm = tbbcstu_stu_pidm
    AND spriden_pidm = sftregs_pidm
    AND (sftregs_pidm, sftregs_credit_hr) IN
    (SELECT DISTINCT sftregs_pidm, SUM(sftregs_credit_hr)
    FROM sftregs, tbbcstu, spriden
    WHERE sftregs_term_code = '201010'
    AND sftregs_pidm = tbbcstu_stu_pidm
    AND sftregs_pidm = spriden_pidm
    GROUP BY sftregs_pidm)
    AND (tbraccd_pidm, tbraccd_amount) IN
    (SELECT DISTINCT tbraccd_pidm, SUM(tbraccd_amount)
    -- tuition
    FROM tbraccd, tbbcstu, spriden
    WHERE tbraccd_term_code = '201010'
    AND (tbraccd_detail_code = 'TU01' OR
    tbraccd_detail_code = 'TU02' OR
    tbraccd_detail_code = 'TU03' OR
    tbraccd_detail_code = 'TU04')
    AND tbraccd_pidm = tbbcstu_stu_pidm
    AND tbraccd_pidm = spriden_pidm
    GROUP BY tbraccd_pidm)
    --this code works up to this point
    --when I add the next query I get nothing
    AND (tbraccd_pidm, tbraccd_amount) IN
    (SELECT tbraccd_pidm, SUM(tbraccd_amount)
    books
    FROM tbraccd, tbbcstu
    WHERE tbraccd_term_code = '201010'
    AND (tbraccd_detail_code = 'BKSU' OR
    tbraccd_detail_code = 'BKCH')
    AND tbraccd_pidm = tbbcstu_stu_pidm
    GROUP BY tbraccd_pidm, tbraccd_amount)
    --AND (tbraccd_pidm, tbraccd_amount) IN
    -- (SELECT tbraccd_pidm, SUM(tbraccd_amount)
    -- misc
    -- FROM tbraccd, tbbcstu
    -- WHERE tbraccd_term_code = '201010'
    -- AND tbraccd_pidm = tbbcstu_stu_pidm
    -- AND (tbraccd_detail_code = 'AUNA' OR
    -- tbraccd_detail_code = 'OTPB')
    -- GROUP BY tbraccd_pidm, tbraccd_amount)
    --ORDER BY tbraccd_pidm, spriden_first_name, spriden_mi, spriden_last_name,
    -- tbbcstu_sponsor_ref_number, sftregs_credit_hr;
    ORDER BY tbraccd_pidm;
    BEGIN
    v_filehandle := utl_file.fopen(location => 'UTLFILE_MISAP9',
    filename => 'ban_matrix.dat',
    open_mode => 'w',
    max_linesize => 32767);
    OPEN c_sel_contract;
    LOOP
    DBMS_OUTPUT.PUT_LINE('looping');
    FETCH c_sel_contract INTO v_contract_id, v_contract_name,
    v_contract_addr1, v_contract_addr2,
    v_contract_city, v_contract_stat,
    v_contract_zip;
    EXIT WHEN c_sel_contract%NOTFOUND;
    v_output :=
    nvl(rpad(v_contract_id,9),rpad(' ',9)) ||
    ' ' ||
    nvl(rpad(v_contract_name,60),rpad(' ',60));
    utl_file.put_line(v_filehandle,v_output);
    v_output :=
    nvl(rpad(v_contract_addr1, 30),rpad(' ',30)) ||
    ' ' ||
    nvl(rpad(v_contract_addr2, 30),rpad(' ',30));
    utl_file.put_line(v_filehandle,v_output);
    v_output :=
    nvl(rpad(v_contract_city, 20), rpad(' ',20)) ||
    ' ' ||
    nvl(rpad(v_contract_stat, 3), rpad(' ',3)) ||
    ' ' ||
    nvl(rpad(v_contract_zip, 10), rpad(' ',10));
    utl_file.put_line(v_filehandle,v_output);
    utl_file.new_line(v_filehandle);
    OPEN c_sel_student;
    LOOP
    FETCH c_sel_student into v_student_id, v_student_first_name, v_student_mid_name,
    v_student_last_name,
    v_credit_hrs,
    v_tuition_amount,
    v_sftregs_pidm,
    v_tbraccd_pidm;
    -- v_books_amount, v_misc_amount;
    EXIT WHEN c_sel_student%NOTFOUND;
    v_last_out := substr(v_student_last_name, 1, 20);
    v_output :=
    nvl(rpad(v_student_id, 09),rpad(' ',09)) ||
    ' ' ||
    nvl(rpad(v_student_first_name, 15),rpad(' ',15)) ||
    nvl(rpad(v_student_mid_name, 15),rpad(' ',15)) ||
    nvl(rpad(v_last_out, 20),rpad(' ',20)) ||
    ' ' ||
    nvl(rpad(v_student_ref_number, 09),rpad(' ',09)) ||
    ' ' ||
    v_credit_hrs ||
    ' ' ||
    v_tuition_amount ||
    -- v_books_amount ||
    -- ' ' ||
    -- v_misc_amount;
    utl_file.put_line(v_filehandle,v_output);
    END LOOP;
    END LOOP;
    --EXCEPTION
    --WHEN OTHERS THEN
    -- DECLARE
    -- err_msg VARCHAR2(100);
    -- BEGIN
    -- err_msg := 'ERR- '||SUBSTR(SQLERRM, 1,100);
    -- - utl_file.put_line(v_filehandle,err_msg);
    --END;
    utl_file.fclose(v_filehandle);
    CLOSE c_sel_contract;
    CLOSE c_sel_student;
    --END AR_MATRIX_PROC;
    END;

    run this original query
    SELECT DISTINCT spriden_id,
            spriden_first_name,
            spriden_mi,
            spriden_last_name,
            sftregs_credit_hr,
            tbraccd_amount,
            sftregs_pidm,
            tbraccd_pidm
       FROM spriden, tbraccd, tbbcstu, sftregs
    WHERE 559220 = tbbcstu_contract_pidm
       AND spriden_pidm = tbraccd_pidm
       AND spriden_pidm = tbbcstu_stu_pidm
       AND spriden_pidm = sftregs_pidm
       AND (sftregs_pidm, sftregs_credit_hr) IN (SELECT DISTINCT sftregs_pidm, SUM(sftregs_credit_hr)
                                                   FROM sftregs, tbbcstu, spriden
                                                  WHERE sftregs_term_code = '201010'
                                                    AND sftregs_pidm = tbbcstu_stu_pidm
                                                    AND sftregs_pidm = spriden_pidm
                                                 GROUP BY sftregs_pidm)
       AND (tbraccd_pidm, tbraccd_amount) IN (SELECT DISTINCT tbraccd_pidm, SUM(tbraccd_amount)
                                              -- tuition
                                                FROM tbraccd, tbbcstu, spriden
                                               WHERE tbraccd_term_code = '201010'
                                                 AND (tbraccd_detail_code = 'TU01' OR
                                                      tbraccd_detail_code = 'TU02' OR
                                                      tbraccd_detail_code = 'TU03' OR
                                                      tbraccd_detail_code = 'TU04')
                                                 AND tbraccd_pidm = tbbcstu_stu_pidm
                                                 AND tbraccd_pidm = spriden_pidm
                                               GROUP BY tbraccd_pidm)
       AND (tbraccd_pidm, tbraccd_amount) IN (SELECT tbraccd_pidm, SUM(tbraccd_amount) books
                                                FROM tbraccd, tbbcstu
                                               WHERE tbraccd_term_code = '201010'
                                                 AND (tbraccd_detail_code = 'BKSU' OR
                                                      tbraccd_detail_code = 'BKCH')
                                                 AND tbraccd_pidm = tbbcstu_stu_pidm
                                              GROUP BY tbraccd_pidm, tbraccd_amount)
    ORDER BY tbraccd_pidm;then run this sub-query:
    SELECT tbraccd_pidm, SUM(tbraccd_amount) books
       FROM tbraccd, tbbcstu
      WHERE tbraccd_term_code = '201010'
        AND (tbraccd_detail_code = 'BKSU' OR
             tbraccd_detail_code = 'BKCH')
       AND tbraccd_pidm = tbbcstu_stu_pidm
    GROUP BY tbraccd_pidm, tbraccd_amount)see if you have a matching tbraccd_pidm and tbraccd_amount between the two results.

  • How to find out which sub query returns more than one row

    Hi all,
    Can any one give me clue ,how to find out which sub query returns more than one row in the following query .
    /* Formatted on 2011/05/17 19:22 (Formatter Plus v4.8.8) */
    SELECT a.*, ROWNUM AS rnm
      FROM (SELECT DISTINCT '1' AS "Page View", ou.org_unit_name AS "Org",
                            prxm.mbr_idntfr AS "Beneficiary ID",
                               md.last_name
                            || ', '
                            || md.first_name AS "Beneficiary Name",
                            pci.idntfr AS "Tracking No.",
                            TO_CHAR (TRUNC (req.pa_rqst_date),
                                     'MM/dd/yyyy'
                                    ) AS "Request Date",
                            sts.status_name AS "Status",
                            req.pa_rqst_sid AS "Request #",
                            prxm.mbr_sid AS "Mbr_sid",
                            TO_CHAR
                                  (TRUNC (req.pa_revision_date),
                                   'MM/dd/yyyy'
                                  ) AS "Last Updated",
                            TO_CHAR (psd.TO_DATE, 'MM/dd/yyyy') AS "TO_DATE",
                            prxpl.prvdr_lctn_iid AS "PRVDR_LCTN_IID",
                            pd.prvdr_sid AS "PRVDR_SID", 'Y' AS "State View",
                            DECODE
                               ((SELECT DISTINCT pd.national_prvdr_idntfr
                                            FROM pa_request_x_provider_location prxplo
                                           WHERE prxplo.pa_rqst_sid =
                                                                   req.pa_rqst_sid
                                             AND prxplo.oprtnl_flag = 'A'
                                             AND prxplo.pa_prvdr_type_lkpcd = 'RR'),
                                0, (SELECT prxplo.prvdr_lctn_idntfr
                                      FROM pa_request_x_provider_location prxplo
                                     WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid
                                       AND prxplo.oprtnl_flag = 'A'
                                       AND prxplo.pa_prvdr_type_lkpcd = 'RR'),
                                NULL, (SELECT prxplo.prvdr_lctn_idntfr
                                         FROM pa_request_x_provider_location prxplo
                                        WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid
                                          AND prxplo.oprtnl_flag = 'A'
                                          AND prxplo.pa_prvdr_type_lkpcd = 'RR'),
                                (SELECT DISTINCT pd.national_prvdr_idntfr
                                            FROM pa_request_x_provider_location prxplo
                                           WHERE prxplo.pa_rqst_sid =
                                                                   req.pa_rqst_sid
                                             AND prxplo.oprtnl_flag = 'A'
                                             AND prxplo.pa_prvdr_type_lkpcd = 'RR')
                               ) AS "NPI/ID",
                            DECODE
                               ((SELECT pd.org_bsns_name
                                   FROM pa_request_x_provider_location prxplo
                                  WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid
                                    AND prxplo.oprtnl_flag = 'A'
                                    AND prxplo.pa_prvdr_type_lkpcd = 'RR'),
                                NULL, (SELECT    pd.last_name
                                              || ', '
                                              || pd.first_name
                                              || ' '
                                              || pd.middle_name
                                         FROM pa_request_x_provider_location prxplo
                                        WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid
                                          AND prxplo.oprtnl_flag = 'A'
                                          AND prxplo.pa_prvdr_type_lkpcd = 'RR'),
                                (SELECT pd.org_bsns_name
                                   FROM pa_request_x_provider_location prxplo
                                  WHERE prxplo.pa_rqst_sid = req.pa_rqst_sid
                                    AND prxplo.oprtnl_flag = 'A'
                                    AND prxplo.pa_prvdr_type_lkpcd = 'RR')
                               ) AS "Prvdr Name",
                            TO_CHAR (psd.from_date,
                                     'MM/dd/yyyy'
                                    ) AS "Srvc From Date",
                            TO_CHAR (req.validity_start_date,
                                     'MM/DD/YYYY'
                                    ) AS "Due Date",
                            (fn_get_busniess_days (TRUNC (req.validity_start_date))
                            ) AS "Days<br>Left",
                            req.pa_mode_type_lkpcd AS "Source",
                            TO_CHAR (TRUNC (wmdtl.rtng_date),
                                     'MM/dd/yyyy'
                                    ) AS "Assigned On",
                            NVL (wmdtl.assigned_to_user_name,
                                 'Not Assigned'
                                ) AS "Assigned To",
                            req.org_unit_sid AS "OrgUnitSid",
                            TO_CHAR
                                 (wmdtl.modified_date,
                                  'MM/dd/yyyy hh24:mi:ss'
                                 ) AS "WTRD_MODIFIED_DATE",
                            TO_CHAR (wmdtl.rtng_date,
                                     'MM/dd/yyyy'
                                    ) AS "WTRD_RTNG_DATE",
                            req.status_cid AS "PA_STATUS_CID",
                            TO_CHAR (req.modified_date,
                                     'MM/dd/yyyy'
                                    ) AS "PA_REQ_MODIFIED_DATE",
                            prs.state_pa_srvc_type_code
                                                     AS "STATE_PA_SRVC_TYPE_CODE",
                            wmdtl.wm_pa_task_rtng_dtl_sid
                                                        AS "WM_TASK_RTNG_DTL_SID",
                            wmdtl.assigned_to_user_acct_sid
                                              AS "WTRD_Assigned_to_user_acct_sid",
                            (fn_get_busniess_days (TRUNC (req.validity_start_date))
                            ) AS "Days<br>LeftSort",
                            wmdtl.assigned_to_org_unit_sid
                                                  AS "WTRD_Assigned_to_OrgUntSid",
                            DECODE
                               ((SELECT COUNT (*)
                                   FROM pa_request_status prs
                                  WHERE prs.pa_rqst_sid = req.pa_rqst_sid
                                    AND prs.status_cid = 5
                                    AND prs.oprtnl_flag = 'I'),
                                0, 'N',
                                'Y'
                               ) AS "SHOW_UTILIZATION"
                       FROM   pa_request req,
                             pa_certification_identifier pci,
                             status sts,
                             pa_request_x_member prxm,
                             wm_pa_task_routing_detail wmdtl,
                             pa_service_date psd,
                             org_unit ou,
                             pa_request_service prs,
                             pa_request_x_provider_location prxpl,
                             provider_location pl,
                             provider_detail pd,
                             provider p,
                             mbr_dmgrphc md
                      WHERE req.oprtnl_flag = 'A'
                        AND req.status_cid NOT IN
                                     (20, 30, 70, 25, 80, 96, 85, 5, 97, 98, 101)
                        AND req.org_unit_sid IN
                               (3057, 3142, 3058, 3143, 3059, 3144, 3060, 3145,
                                3061, 3146, 3062, 3147, 3063, 3148, 3064, 3149,
                                3065, 3150, 3066, 3151, 3067, 3152, 3068, 3153,
                                3069, 3154, 3070, 3155, 3071, 3156, 3072, 3157,
                                3073, 3158, 3074, 3159, 3075, 3160, 3076, 3161,
                                3077, 3162, 3078, 3163, 3079, 3164, 3080, 3165,
                                3081, 3166, 3082, 3167, 3083, 3168, 3084, 3169,
                                3085, 3170, 3086, 3171, 3087, 3172, 3088, 3173,
                                3089, 3174, 3090, 3175, 3091, 3176, 3092, 3177,
                                3093, 3178, 3094, 3179, 3095, 3180, 3096, 3181,
                                3097, 3182, 3098, 3183, 3099, 3184, 3100, 3185,
                                3101, 3186, 3102, 3187, 3103, 3003, 75000104,
                                75000108, 2006, 75000103, 75000102, 75000113,
                                75000111, 75000109, 2001, 2009, 75000105,
                                75000107, 2004, 2010, 2013, 2014, 2005, 2011,
                                75000112, 2002, 1001, 2012, 75000106, 2007,
                                75000101, 2003, 75000110, 2008, 3001, 3002, 3019,
                                3104, 3020, 3105, 3021, 3106, 3022, 3107, 3023,
                                3108, 3024, 3109, 3025, 3110, 3026, 3111, 3027,
                                3112, 3028, 3113, 3029, 3114, 3030, 3115, 3031,
                                3116, 3032, 3117, 3033, 3118, 3034, 3119, 3035,
                                3120, 3036, 3121, 3037, 3122, 3038, 3123, 3039,
                                3124, 3040, 3125, 3041, 3126, 3042, 3127, 3043,
                                3128, 3044, 3129, 3045, 3130, 3046, 3131, 3047,
                                3132, 3048, 3133, 3049, 3134, 3050, 3135, 3051,
                                3136, 3052, 3137, 3053, 3138, 3054, 3139, 3055,
                                3140, 3056, 3141)
                        AND req.pa_rqst_sid = prs.pa_rqst_sid
                        AND prs.oprtnl_flag = 'A'
                        AND prs.pa_rqst_srvc_sid = psd.pa_rqst_srvc_sid
                        AND psd.oprtnl_flag = 'A'
                        AND req.pa_rqst_sid = pci.pa_rqst_sid
                        AND pci.oprtnl_flag = 'A'
                        AND req.pa_rqst_sid = prxm.pa_rqst_sid
                        AND prxm.oprtnl_flag = 'A'
                        AND md.oprtnl_flag = 'A'
                        AND md.status_cid = 2
                        AND TRUNC (SYSDATE) BETWEEN md.from_date AND md.TO_DATE
                        AND prxm.mbr_sid = md.mbr_sid
                        AND ou.org_unit_sid = req.org_unit_sid
                        AND ou.oprtnl_flag = 'A'
                        AND req.pa_rqst_sid = prxpl.pa_rqst_sid
                        AND prxm.pa_rqst_sid = prxpl.pa_rqst_sid
                        AND pci.pa_rqst_sid = prxm.pa_rqst_sid
                        AND pci.pa_rqst_sid = wmdtl.subsystem_task_sid
                        AND pci.pa_rqst_sid = prxpl.pa_rqst_sid
                        AND prxpl.pa_prvdr_type_lkpcd = 'RR'
                        AND prxpl.oprtnl_flag = 'A'
                        AND req.status_cid = sts.status_cid
                        AND sts.status_type_cid = 3
                        AND sts.oprtnl_flag = 'A'
                        AND prxpl.prvdr_lctn_iid = pl.prvdr_lctn_iid
                        AND p.prvdr_sid = pd.prvdr_sid
                        AND p.prvdr_sid = pl.prvdr_sid
                        AND pd.oprtnl_flag = 'A'
                        AND pd.status_cid = 2
                        AND TRUNC (SYSDATE) BETWEEN pd.from_date AND pd.TO_DATE
                        AND wmdtl.subsystem_task_sid = req.pa_rqst_sid
                        AND wmdtl.subsystem_lkpcd = 'PA'
                        AND wmdtl.oprtnl_flag = 'A'
                        AND req.pa_rqst_date > (SYSDATE - 365)
                                       ORDER BY TO_DATE ("Request Date", 'MM/dd/yyyy hh24:mi:ss') DESC,
                            "Beneficiary Name" ASC) a
    WHERE ROWNUM < 102;regards,
    P Prakash
    Edited by: BluShadow on 17-May-2011 15:01
    added {noformat}{noformat} tags around the code                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    833560 wrote:
    Can any one give me clue ,how to find out which sub query returns more than one row in the following query .This is why smaller, simpler queries are easier to work with than huge ones - when something like this goes wrong smaller queries are much eaiser to debug. Unfortunately using smaller, easier-to-work with queries is not always an option
    Ganesh is right - you will have to dissect the big query bit by bit until you find the offending subquery. If there is another way I would like to find out about it too.
    The easiest way to do this is probably to use block comments to isolate parts of the query bit by bit until you find the offending part. If you carefully examine the subqueries you might be able to figure out which one is returning multiple rows without commenting everything
    Good luck!

  • Case Statement in sub query

    Hi, I have two issues, here is my initial code:
    select
    cc.name_id_no
    ,cc.discover_date
    ,cc.cla_case_no
    ,max(rl.year_of_incident)Non_Loss_Past_5
    ,rl.timestamp
    from cla_case cc, rbn_loss rl
    where cc.name_id_no = rl.customer_no
    and rl.year_of_incident < trunc(cc.discover_date)
    and rl.type_of_loss < 1000
    and rl.timestamp < trunc(cc.discover_date)
    and (cc.question_class = 20
    or cc.question_class = 25)
    and (trunc(cc.discover_date)- (rl.year_of_incident)) < 1095
    --and (trunc(cc.discover_date) <> (rl.year_of_incident))
    group by cc.cla_case_no,name_id_no, cc.discover_date,rl.timestamp
    Now a cla_case_no can map to several year_of_incident. I only want the cla_case_no that maps to the max year_of_incident ie There should only be a single cla_case_no corresponding to the max year_of_incident.
    To get around this I did the following which is not very efficient and I'm hoping it can be improved:
    select distinct z.cla_case_no from (
    select
    cc.name_id_no
    ,cc.discover_date
    ,cc.cla_case_no
    ,max(rl.year_of_incident)Non_MW_Loss_Past_5
    ,rl.timestamp
    from cla_case cc, rbn_loss rl
    where cc.name_id_no = rl.customer_no
    and rl.year_of_incident < trunc(cc.discover_date)
    and rl.type_of_loss < 1000
    and rl.timestamp < trunc(cc.discover_date)
    and (cc.question_class = 20
    or cc.question_class = 25)
    and (trunc(cc.discover_date)- (rl.year_of_incident)) < 1095
    --and (trunc(cc.discover_date) <> (rl.year_of_incident))
    group by cc.cla_case_no,name_id_no, cc.discover_date,rl.timestamp
    ) z
    Now comes the second issue: The above is actually a subquery that will link to a bigger table via cla_case_no ccx
    SELECT
    ie ,(select distinct z.cla_case_no from (
    select cc.name_id_no, cc.discover_date ,cc.cla_case_no, max(rl.year_of_incident)Non_MW_Loss_Past_5, rl.timestamp
    from cla_case cc, rbn_loss rl
    where cc.name_id_no = rl.customer_no
    and rl.year_of_incident < trunc(cc.discover_date)
    and rl.type_of_loss < 1000
    and rl.timestamp < trunc(cc.discover_date)
    and (cc.question_class = 20
    or cc.question_class = 25)
    and (trunc(cc.discover_date)- (rl.year_of_incident)) < 1095
    --and (trunc(cc.discover_date) <> (rl.year_of_incident))
    group by cc.cla_case_no,name_id_no, cc.discover_date,rl.timestamp
    ) z
    where z.cla_case_no = ccx.cla_case_no
    ) Non_MW_Loss_Past_5
    FROM etc
    Now only certain cc.cla_case_no from the subquery will corresp to the ccx_cla_case_no from the main table and the other entries will be null.
    What I require is that if the subquery returns a result that IS NOT NULL to return 'Y' ELSE 'N' instead of the varies cla_case_no's and (null) entries in the Non_MW_Loss_Past_5 column
    Thanks!!!
    Banner:
    Oracle Database 11g Release 11.2.0.2.0 - 64bit Production
    PL/SQL Release 11.2.0.2.0 - Production
    "CORE 11.2.0.2.0 Production"
    TNS for Linux: Version 11.2.0.2.0 - Production
    NLSRTL Version 11.2.0.2.0 - Production

    Hi,
    It looks like you have another copy of this question:
    Case Statement and sub query
    That's probably not your fault, but you should mark the other copy as "Answered" right away, and then you'll only have to look for replies in one place.
    885178 wrote:
    ... Now a cla_case_no can map to several year_of_incident. I only want the cla_case_no that maps to the max year_of_incident ie There should only be a single cla_case_no corresponding to the max year_of_incident.If you know there will only be one, then you can use LAST, and you don't need GrOUP BY
    To get around this I did the following which is not very efficient and I'm hoping it can be improved:
    select distinct z.cla_case_no from (
    select
    cc.name_id_no
    ,cc.discover_date
    ,cc.cla_case_no
    ,max(rl.year_of_incident)Non_MW_Loss_Past_5
    ,rl.timestamp
    from cla_case cc, rbn_loss rl
    where cc.name_id_no = rl.customer_no
    and rl.year_of_incident < trunc(cc.discover_date)
    and rl.type_of_loss < 1000
    and rl.timestamp < trunc(cc.discover_date)
    and (cc.question_class = 20
    or cc.question_class = 25)
    and (trunc(cc.discover_date)- (rl.year_of_incident)) < 1095
    --and (trunc(cc.discover_date) <> (rl.year_of_incident))
    group by cc.cla_case_no,name_id_no, cc.discover_date,rl.timestamp
    ) zHere's one way:
    SELECT       MIN (cla_case_no) KEEP (DENSE_RANK LAST ORDER BY r1.year_of_incident)
                         AS latest_cla_case_no
    FROM       cla_case     cc
    ,             rbn_loss      rl
    WHERE     cc.name_id_no          = rl.customer_no
    AND       rl.year_of_incident     > TRUNC (cc.discover_date) - 1095
    AND       rl.year_of_incident      < TRUNC (cc.discover_date)
    AND       rl.type_of_loss     < 1000
    AND       rl.timestamp          < TRUNC (cc.discover_date)
    AND       cc.question_class     IN (20, 25)
    ;If you'd post some sample data (CREATE TABLE and INSERT statements) and the results you want from that data, then I could test this.
    Now comes the second issue: The above is actually a subquery that will link to a bigger table via cla_case_no ccx
    SELECT
    ie ,(select distinct z.cla_case_no from (
    select cc.name_id_no, cc.discover_date ,cc.cla_case_no, max(rl.year_of_incident)Non_MW_Loss_Past_5, rl.timestamp
    from cla_case cc, rbn_loss rl
    where cc.name_id_no = rl.customer_no
    and rl.year_of_incident < trunc(cc.discover_date)
    and rl.type_of_loss < 1000
    and rl.timestamp < trunc(cc.discover_date)
    and (cc.question_class = 20
    or cc.question_class = 25)
    and (trunc(cc.discover_date)- (rl.year_of_incident)) < 1095
    --and (trunc(cc.discover_date) <> (rl.year_of_incident))
    group by cc.cla_case_no,name_id_no, cc.discover_date,rl.timestamp
    ) z
    where z.cla_case_no = ccx.cla_case_no
    ) Non_MW_Loss_Past_5
    FROM etc
    Now only certain cc.cla_case_no from the subquery will corresp to the ccx_cla_case_no from the main table and the other entries will be null.
    What I require is that if the subquery returns a result that IS NOT NULL to return 'Y' ELSE 'N' instead of the varies cla_case_no's and (null) entries in the Non_MW_Loss_Past_5 column
    NVL2 (x, 'Y', 'N')returns 'Y' if x is NULL, and it returns 'N' if x is not NULL. X can be a scalar sub-query:
    NVL2 ((SELECT ...), 'Y', 'N')You could also use an EXISTS sub-query:
    CASE
        WHEN  EXISTS (SELECT ...)
        THEN  'Y'
        ELSE  'N'
    END

  • Sub-query problem on Oracle 10g

    The following query works on Oracle 10.2.0.1.0 on windows,but doesn't work on Oracle 10.2.0.2.0 on Linux.
    Error report: SQL Error: ORA-00904: "T"."AUDIT_USECS": invalid identifier 00904. 00000 - "%s: invalid identifier"
    It works after i remove the sub-query. I found that if use fields of T in sub-query,then error occurs. Is it saying that sub-query can't access the fields in main query?
    What's the problem?
    Is there any grammar erros?If so,what's the right likes?
    Thanks!
    CREATE TABLE AUDITHISTORY(
    CASENUM numeric(20, 0) NOT NULL,
    AUDIT_DATE date NOT NULL,
    USER_NAME varchar(255) NULL,
    AUDIT_USECS numeric(6, 0) NOT NULL,
    TYPE_ID INT NOT NULL )
    Query:
    SELECT T.CASENUM,
    T.USER_NAME,
    T.AUDIT_DATE AS STARTED,
    (SELECT *
    FROM (SELECT S.AUDIT_DATE
    FROM AUDITHISTORY S
    WHERE S.CASENUM=T.CASENUM AND TYPE_ID=2
    AND S.USER_NAME=T.USER_NAME
    AND (S.AUDIT_DATE > T.AUDIT_DATE OR (S.AUDIT_DATE = T.AUDIT_DATE AND S.AUDIT_USECS > T.AUDIT_USECS))
    ORDER BY S.AUDIT_DATE ASC,S.AUDIT_USECS ASC
    ) WHERE rownum <= 1) AS ENDED
    FROM AUDITHISTORY T WHERE TYPE_ID=1
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Prod PL/SQL Release 10.2.0.1.0 - Production
    CORE 10.2.0.1.0 Production
    TNS for 32-bit Windows: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - Production
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.2.0 - Prod PL/SQL Release 10.2.0.2.0 - Production
    CORE 10.2.0.2.0 Production
    TNS for Linux: Version 10.2.0.2.0 - Production
    NLSRTL Version 10.2.0.2.0 - Production

    Try this way:
    SQL> select * from AUDITHISTORY;
       CASENUM AUDIT_DAT USER_NAME            AUDIT_USECS    TYPE_ID
            10 12-MAR-10 USER                         100          1
            10 14-MAR-10 USER                         100          2
            10 16-MAR-10 USER                         100          2
    SQL> SELECT T.CASENUM,
      2  T.USER_NAME,
      3  T.AUDIT_DATE AS STARTED,
      4  (SELECT max(S.AUDIT_DATE) keep (dense_rank first order by S.AUDIT_DATE ASC,S.AUDIT_USECS ASC)
      5   from AUDITHISTORY S  WHERE S.CASENUM=T.CASENUM AND TYPE_ID=2
      6  AND S.USER_NAME=T.USER_NAME
      7  AND (S.AUDIT_DATE > T.AUDIT_DATE OR
      8       (S.AUDIT_DATE = T.AUDIT_DATE AND S.AUDIT_USECS > T.AUDIT_USECS))
      9  ) as ended
    10  FROM AUDITHISTORY T WHERE TYPE_ID=1;
       CASENUM USER_NAME            STARTED   ENDED
            10 USER                 12-MAR-10 14-MAR-10Max
    http://oracleitalia.wordpress.com

  • Joining with sub query not working

    Hi
    I am new with these complex queries. I am trying to join a sub query to a query as below;
    SELECT Events1.InvoiceBatch AS BatchNo, Events1.InvoiceBatchDate AS BatchDate, tblClients.Company, tblClients.ID AS ClientID, COUNT(Events1.ID) AS Invoices,
    COUNT(*) - COUNT(Events1.InvoicePrintDate) AS E, Events1.InvoiceBatchFromDate AS BatchFrom, Events1.InvoiceBatchToDate AS BatchTo, (SELECT EventID, SUM(Total) FROM tblStaffBookings AS StaffBookings WHERE StaffBookings.EventID = Events1.ID GROUP BY EventID) AS Total
    FROM tblEvents AS Events1 LEFT OUTER JOIN
    tblClients ON Events1.ClientID = tblClients.ID
    WHERE (Events1.FactoringExportDate IS NULL) OR (Events1.AccountsExportDate IS NULL) OR (Events1.InvoiceSentDate IS NULL)
    GROUP BY Events1.InvoiceBatch, Events1.InvoiceBatchDate, tblClients.Company, tblClients.ID, Events1.InvoiceBatchFromDate, Events1.InvoiceBatchToDate
    HAVING (Events1.InvoiceBatch = 5212)
    ORDER BY tblClients.Company
    I am getting these two errors;
    Msg 8120, Level 16, State 1, Line 2
    Column 'tblEvents.ID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
    Msg 116, Level 16, State 1, Line 2
    Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
    What am I missing?
    Thanks
    Regards

    SELECT Events1.InvoiceBatch AS BatchNo, Events1.InvoiceBatchDate AS BatchDate, tblClients.Company, tblClients.ID AS ClientID, COUNT(Events1.ID) AS Invoices,
    COUNT(*) - COUNT(Events1.InvoicePrintDate) AS E, Events1.InvoiceBatchFromDate AS BatchFrom, Events1.InvoiceBatchToDate AS BatchTo,Total
    FROM tblEvents AS Events1 LEFT OUTER JOIN
    tblClients ON Events1.ClientID = tblClients.ID
    LEFT OUTER JOIN (SELECT EventID, SUM(Total) AS Total FROM tblStaffBookings AS StaffBookings WHERE StaffBookings.EventID = Events1.ID GROUP BY EventID) sb
    ON sb.EventID = Events1.ID
    WHERE (Events1.FactoringExportDate IS NULL) OR (Events1.AccountsExportDate IS NULL) OR (Events1.InvoiceSentDate IS NULL)
    GROUP BY Events1.InvoiceBatch, Events1.InvoiceBatchDate, tblClients.Company, tblClients.ID, Events1.InvoiceBatchFromDate, Events1.InvoiceBatchToDate,Total
    HAVING (Events1.InvoiceBatch = 5212)
    ORDER BY tblClients.Company
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page
    Says;
    Msg 4104, Level 16, State 1, Line 5
    The multi-part identifier "Events1.ID" could not be bound.
    on
    LEFT OUTER JOIN (SELECT EventID, SUM(Total) AS Total FROM tblStaffBookings AS StaffBookings WHERE StaffBookings.EventID = Events1.ID GROUP BY EventID) sb
    Regards

  • Best way to outer join a table that is doing a sub query

    RDBMS : 11.1.0.7.0
    Hello,
    What is the best way to outer join a table that is doing a sub query? This is a common scenario in EBS for the date tracked tables.
    SELECT papf.full_name, fu.description
      FROM fnd_user fu
          ,per_all_people_f papf
    WHERE fu.user_id = 1772
       AND fu.employee_id = papf.person_id(+)
       AND papf.effective_start_date = (SELECT MAX( per1.effective_start_date )
                                          FROM per_all_people_f per1
                                         WHERE per1.person_id = papf.person_id)Output:
    No output produced because the outer join cannot be done on the sub queryIn this case I did a query in the FROM clause. Is this my best option?
    SELECT papf.full_name, fu.description
      FROM fnd_user fu
          ,(SELECT full_name, person_id
              FROM per_all_people_f papf
             WHERE papf.effective_start_date = (SELECT MAX( per1.effective_start_date )
                                                  FROM per_all_people_f per1
                                                 WHERE per1.person_id = papf.person_id)) papf
    WHERE fu.user_id = 1772
       AND fu.employee_id = papf.person_id(+)Output:
    FULL_NAME     DESCRIPTION
    {null}            John DoeThanks,
    --Johnnie                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Hi,
    BrendanP wrote:
    ... See the adjacent thread for the other with Row_Number().Do you mean {message:id=10564772} ? Which threads are adjacent is always changing. Post a link.
    I think RANK suits the requirements better than ROW_NUMBER:
    WITH    all_matches     AS
         SELECT  papf.full_name
         ,      fu.description
         ,     RANK () OVER ( PARTITION BY  papf.person_id
                               ORDER BY          papf.effective_start_date     DESC
                        )           AS r_num
         FROM             fnd_user             fu
         LEFT OUTER JOIN      per_all_people_f  papf  ON  fu.employee_id  = papf.person_id
         WHERE   fu.user_id  = 1772
    SELECT     full_name
    ,     description
    FROM     all_matches
    WHERE     r_num     = 1
    Johnnie: I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
    See the forum FAQ {message:id=9360002}

  • SELECT records larger than date specified in sub query

    Dear All
    Thank you for your attention.
    I would like to select records larger than date specified in sub query
    query should be something like the following
    SELECT my_order_number, my_date, my_task
    FROM MYTB
    WHERE my_order_number IN order_no AND my_date > date (SELECT order_no, date FROM MySubQueryResult)
     (it is incorrect)
    Sub query result:
    order_no | date
    A1    | 2014-12-21 09:06:00
    A2    | 2014-12-20 09:07:00
    A3    | 2014-12-20 08:53:00
    A4    | 2014-12-20 08:57:00
    MYTB:
    my_order_number | my_task | my_date
    A1  |  T1  |  2014-12-21 09:06:00
    A1  |  T2  |  2014-12-22 10:01:00
    A2  |  T1  |  2014-12-20 09:07:00
    A3  |  T2  |  2014-12-20 08:53:00
    A3  |  T4  |  2014-12-21 09:30:00
    A3  |  T8  |  2014-12-23 20:32:00
    A4  |  T6  |  2014-12-20 08:57:00
    expected result:
    my_order_number |  my_task | my_date
    A1  |  T2  |  2014-12-22 10:01:00
    A3  |  T4  |  2014-12-21 09:30:00
    A3  |  T8  |  2014-12-23 20:32:00
    Any ideas?  Thanks.
    swivan

    Hi,
    try this
    SELECT my_order_number, my_date, my_task
    FROM MYTB
    WHERE my_order_number IN (SELECT order_no FROM MySubQueryResult)
    AND my_date > (SELECT date FROM MySubQueryResult)
    Alternatively, you can also make use of joins to achieve the same.
    Please mark solved if I've answered your question, vote for it as helpful to help other users find a solution quicker
    Praveen Dsa | MCITP - Database Administrator 2008 |
    My Blog | My Page
    Dear Praveen Dsa
    Thanks for your reply, but order_no and date are paired and related, cannot separate.
    each order have its own date, so it is not working
    Best Regards
    swivan

  • How to rewrite this query without sub query please help me

    Hello All Good Evening,
    Could you please help me with this query, how can i write this query without sub query, or how can write this query another ways
    please help me
    select planno, status1, count(*) Counts from
    select a.ValetNO PlanNo  ,
    case 
         when JoinCode in ('00', '01', '02') then 'Actcess'
         when JoinCode in ('20', '21', '22', '23','38', '39') then
         'Secured' else 'Other' end Status1 ---, COUNT (*)
       from  dbo.ppt a(NOLOCK)  left join dbo.acts b on a.P_ID = b.P_ID and a.ValetNO  = b.ValetNO
    --group by a.ValetNO
      a group by planno, status1
    order by 2
    Thank you in Advance
    Milan

    Whats your objective here? Sorry, am not able to understand the reason for this change. 
    Try the below:(Not tested)
    ;With cte
    As
    select a.ValetNO PlanNo ,
    case
    when JoinCode in ('00', '01', '02') then 'Actcess'
    when JoinCode in ('20', '21', '22', '23','38', '39') then
    'Secured' else 'Other' end Status1 ---, COUNT (*)
    from dbo.ppt a(NOLOCK) left join dbo.acts b on a.P_ID = b.P_ID and a.ValetNO = b.ValetNO
    select planno, status1, count(*) Counts from cte
    a group by planno, status1
    order by 2
    Even below:
    select a.ValetNO PlanNo ,
    case
    when JoinCode in ('00', '01', '02') then 'Actcess'
    when JoinCode in ('20', '21', '22', '23','38', '39') then
    'Secured' else 'Other' end Status1 , COUNT (1)
    from dbo.ppt a(NOLOCK) left join dbo.acts b on a.P_ID = b.P_ID and a.ValetNO = b.ValetNO
    Group by a.ValetNO ,
    case
    when JoinCode in ('00', '01', '02') then 'Actcess'
    when JoinCode in ('20', '21', '22', '23','38', '39') then
    'Secured' else 'Other' end

  • Sub Query Error When Passing Dynamic Parameter.

    Dear All, I need help for below query problem.
    I have try below query run no problem when pass a static Parameter into the query but it throw error once i have add in the dynamic parameter:-
    --Sales BatchNum Transaction
    SELECT T0.[ItemCode], T0.[ItemName], T0.[WhsCode], T0.[BatchNum], ISNULL(T4.[AvgPrice],0) AS 'Avg Price', SUM(T0.[Quantity]) AS 'Sales Quantity',
    (SELECT [Quantity] FROM [OIBT] T1 WHERE T1.[ItemCode] = T0.[ItemCode] AND T1.[WhsCode] = T0.[WhsCode] AND T1.[BatchNum]=T0.[BatchNum]) AS 'Stock OnHand'
    FROM [IBT1] T0 INNER JOIN [OITM] T2 ON T0.[ItemCode] = T2.[ItemCode]
                      INNER JOIN [OITB] T3 ON T2.[ItmsGrpCod] = T3.[ItmsGrpCod]
                      INNER JOIN [OITW] T4 ON T0.[ItemCode] = T4.[ItemCode] AND T0.[WhsCode] = T4.[WhsCode]
    WHERE T0.[BaseType] = [%0] AND T0.[DocDate] BETWEEN [%1] AND [%2] AND T3.[ItmsGrpNam] = [%3]
    GROUP BY T0.[ItemCode], T0.[ItemName], T0.[WhsCode], T0.[BatchNum], T4.[AvgPrice]
    --ORDER BY T0.[ItemCode]
    UNION ALL
    --No Sales Batch Transaction
    SELECT T4.[ItemCode], T4.[ItemName],T4.[WhsCode], T4.[BatchNum], ISNULL(T7.[AvgPrice],0) AS 'Avg Price', 0 AS 'Sales Quantity' ,SUM(T4.[Quantity])
    FROM [OIBT] T4 INNER JOIN [OITM] T5 ON T4.[ItemCode] = T5.[ItemCode]
                      INNER JOIN [OITB] T6 ON T5.[ItmsGrpCod] = T6.[ItmsGrpCod]
                      INNER JOIN [OITW] T7 ON T4.[ItemCode] = T7.[ItemCode] AND T4.[WhsCode] = T7.[WhsCode]
    WHERE NOT EXISTS
    ( SELECT T0.[ItemCode], T0.[ItemName], T0.[WhsCode], T0.[BatchNum], ISNULL(T5.[AvgPrice],0) AS 'Avg Price', SUM(T0.[Quantity]) AS 'Sales Quantity'
      FROM [IBT1] T0 INNER JOIN [OITM] T2 ON T0.[ItemCode] = T2.[ItemCode]
                        INNER JOIN [OITB] T3 ON T2.[ItmsGrpCod] = T3.[ItmsGrpCod]
                         INNER JOIN [OITW] T5 ON T0.[ItemCode] = T5.[ItemCode] AND T0.[WhsCode] = T5.[WhsCode]
      WHERE T0.[BaseType] = [%1] AND T0.[DocDate] BETWEEN [%1] AND [%2] AND T4.[ItemCode]=T0.[ItemCode] AND T4.[WhsCode]=T0.[WhsCode] AND T4.[BatchNum]=t0.[BatchNum] AND T3.[ItmsGrpNam] = [%3]
      GROUP BY T0.[ItemCode], T0.[ItemName], T0.[WhsCode], T0.[BatchNum],T5.[AvgPrice]
    AND T6.[ItmsGrpNam] = [%3]
    GROUP BY T4.[ItemCode], T4.[ItemName], T4.[WhsCode], T4.[BatchNum], T7.[AvgPrice]
    HAVING SUM(T4.[Quantity]) > 0
    ORDER BY 1, 2, 3, 5 DESC
    I think SAP Query Manager can support the sub-query, kindly advise how to solve or other alternative way to solve this issue.
    Thanks a lot.

    Dear  Thanga Raj K,
    From your solution i can get my expected result, only within your solution you miss out the @ in line 32 for ToDate variable.
    After i have added it, it working perfectly.
    Thanks once again.
    For other user References code(Corrected):-
    Declare @basetype as int
    Declare @FromDate as Datetime
    Declare @ToDate as Datetime
    Declare @ItemGroup as nvarchar(30)
    set @basetype = (select max(s0.BaseType) from IBT1 S0 where s0.BaseType = '[%0]')
    set @FromDate = (select min(S1.DocDate) from IBT1 S1 where S1.DocDate >= '[%1]')
    set @ToDate = (select max(S2.DocDate) from IBT1 S2 where S2.DocDate <= '[%2]')
    set @ItemGroup = (select max(S3.ItmsGrpNam) from OITB s3 where S3.ItmsGrpNam = '[%3]')
    --Sales BatchNum Transaction
    SELECT T0.ItemCode, T0.ItemName, T0.WhsCode, T0.BatchNum, ISNULL(T4.AvgPrice,0) AS 'Avg Price', SUM(T0.Quantity) AS 'Sales Quantity',
    (SELECT Quantity FROM OIBT T1 WHERE T1.ItemCode = T0.ItemCode AND T1.WhsCode = T0.WhsCode AND T1.BatchNum=T0.BatchNum) AS 'Stock OnHand'
    FROM IBT1 T0 INNER JOIN OITM T2 ON T0.ItemCode = T2.ItemCode
    INNER JOIN OITB T3 ON T2.ItmsGrpCod = T3.ItmsGrpCod
    INNER JOIN OITW T4 ON T0.ItemCode = T4.ItemCode AND T0.WhsCode = T4.WhsCode
    WHERE T0.BaseType = @basetype AND T0.DocDate BETWEEN @FromDate AND @ToDate AND T3.ItmsGrpNam = @ItemGroup
    GROUP BY T0.ItemCode, T0.ItemName, T0.WhsCode, T0.BatchNum, T4.AvgPrice
    --ORDER BY T0.ItemCode
    UNION ALL
    --No Sales Batch Transaction
    SELECT T4.ItemCode, T4.ItemName,T4.WhsCode, T4.BatchNum, ISNULL(T7.AvgPrice,0) AS 'Avg Price', 0 AS 'Sales Quantity' ,SUM(T4.Quantity)
    FROM OIBT T4 INNER JOIN OITM T5 ON T4.ItemCode = T5.ItemCode
    INNER JOIN OITB T6 ON T5.ItmsGrpCod = T6.ItmsGrpCod
    INNER JOIN OITW T7 ON T4.ItemCode = T7.ItemCode AND T4.WhsCode = T7.WhsCode
    WHERE NOT EXISTS
    (SELECT T0.ItemCode, T0.ItemName, T0.WhsCode, T0.BatchNum, ISNULL(T5.AvgPrice,0) AS 'Avg Price', SUM(T0.Quantity) AS 'Sales Quantity'
    FROM IBT1 T0 INNER JOIN OITM T2 ON T0.ItemCode = T2.ItemCode
    INNER JOIN OITB T3 ON T2.ItmsGrpCod = T3.ItmsGrpCod
    INNER JOIN OITW T5 ON T0.ItemCode = T5.ItemCode AND T0.WhsCode = T5.WhsCode
    WHERE T0.BaseType = @basetype AND T0.DocDate BETWEEN @FromDate AND @ToDate AND T4.ItemCode=T0.ItemCode AND T4.WhsCode=T0.WhsCode AND T4.BatchNum=t0.BatchNum AND T3.ItmsGrpNam = @ItemGroup
    GROUP BY T0.ItemCode, T0.ItemName, T0.WhsCode, T0.BatchNum,T5.AvgPrice
    AND T6.ItmsGrpNam = @ItemGroup
    GROUP BY T4.ItemCode, T4.ItemName, T4.WhsCode, T4.BatchNum, T7.AvgPrice
    HAVING SUM(T4.Quantity) > 0
    ORDER BY 1, 2, 3, 5 DESC

  • Max (date) in sub-query

    I have an issue with a big view and several queries running on it where the max (date) is required in the sub-select (example below). When I run traces and explain, the perf problem is when the where cluase is evaluated, the view is pulled second time - so I basically use this view twice. The fact that the date in the underlined table is indexed did not help.
    I tried to use "ROW_NUMBER() OVER (ORDER BY date ASC) AS row_number, " rather to select the max(date) in teh sub query but I get only 1 records returned by the query instead the expected about 25,000.
    Need help on how to correct the max(date) to perform better and also to understand how to correct the ROW_NUMBER() not to limit me to 1 row.
    Thanks a lot for the help, Tom
    create view test_date as select * from user_objects;
    select * --(I have specific columns in the real query)
    from test_date t1
    where LAST_DDL_TIME in
    (select max(LAST_DDL_TIME)
    from test_date t2
    where t1.OBJECT_ID=t2.OBJECT_ID --(more clauses to limit the result but not reflecting the problem)
    and t1.OBJECT_NAME =t2.OBJECT_NAME
    and OBJECT_TYPE not in('TABLE')
    group by t2.OBJECT_ID , t2.OBJECT_NAME )

    I got the query to run - with dense ranck and row-Number I get the same results. My partition by cluse was wrong. But the perfromance is not much better.
    Any other idea on how to optimize a query that uses pattern like below and needs to return all rows from a table that have the max enter date.
    Thanks a lot, tom
    Example:
    col1 col2 col3
    1 sysdate 'I need this record'
    2 sysdate 'I need this record'
    3 sysdate 'I need this record'
    4 sysdate 'I do NOT need this record'
    5 sysdate 'I do NOT need this record'
    5 sysdate+3 'I need this record'
    5 sysdate+2 'I do NOT need this record'
    4 sysdate+3 'I need this record'
    4 sysdate+2 'I do NOT need this record'
    4 sysdate+1 'I do NOT need this record'
    My query corrently is using the following construcion:
    select col1, col2 , col3
    from test_table t
    where 1,2,3
    and col3 = (select max(col3) from test_table t2 where t2.col1 = t.col1) group by t2.col1

  • See my query problem for sub query

    hi master
    Sir see my query
    select lpad(' ',2*(level-1)) || to_char(chartofacc.child),parent,accid as accounted ,title,
    case when fstatus=1 then
    (select sum(drbal) from accbal where parent = accounted)
    when fstatus is null then
    (select drbal from accbal where accid = accounted)
    end subtotal
    from chartofacc
    start with chartofacc.parent is null
    connect by prior chartofacc.child = chartofacc.parent order by chartofacc.accid
    I try but not success how I pass main query value or code in sub query or inner query
    My requirement is inner query get total from accbal table how have accid that in main query accid or accounted
    How I pass main query value or accid code to inner query and inner query give result as per main query accid
    How I get subtotal and total by one query
    Please give me idea or code
    Thanking you
    aamir

    You could write your main SELECT statement as inline view or use the WITH clause, like this:
    WITH ctf AS (SELECT LPAD (' ', 2 * (LEVEL - 1)) || TO_CHAR (chartofacc.CHILD), PARENT,
                        accid AS accounted, title,
                   FROM chartofacc
                  START WITH chartofacc.PARENT IS NULL
                  CONNECT BY PRIOR chartofacc.CHILD = chartofacc.PARENT
                  ORDER BY chartofacc.accid
    SELECT ctf.*,
           CASE WHEN fstatus = 1
                THEN (SELECT SUM (drbal)
                        FROM accbal
                       WHERE PARENT = accounted)
                WHEN fstatus IS NULL
                THEN (SELECT drbal
                        FROM accbal
                       WHERE accid = accounted)
           END subtotal
      FROM ctf
    not tested
    C.

  • Recursive Sub-query Factoring vs Hierarchical Query

    Experts,
    The below are two queries i am executing by using classical approach hierarchical and newest recursive sub-query.Problem is output was different for recursive sub-query factoring, as this is not showing parent-child approach, while connect by prior is showing parent-child fashion.Query 1, i am using hierarchical as it showing correct output parent-child approach, while Query 2 is displaying all the level 1 nodes and then level 2 nodes.I want query 2 output to be same as query 1.Please modify query 2 as required.
    Note:The output of the both queries won't be in displayed as it was in sqlplus, or toad.Please copy and use in your command prompts.
    QUERY 1:
    with main as(select 1 id,'john' name,null mgrid from dual union all
    select 2 id,'michael' name,null mgrid from dual union all
    select 3 id,'peter' name,null mgrid from dual union all
    select 4 id,'henry' name,1 mgrid from dual union all
    select 5 id,'nick' name,2 mgrid from dual union all
    select 6 id,'pao' name,3 mgrid from dual union all
    select 7 id,'kumar' name,3 mgrid from dual union all
    select 8 id,'parker' name,3 mgrid from dual union all
    select 9 id,'mike' name,5 mgrid from dual),
    select lpad(' ',2*(level-1))||name name,level from main start with mgrid is null connect by prior id=mgrid;
    OUTPUT :
    NAME LEVEL
    john 1
    henry 2
    michael 1
    nick 2
    mike 3
    peter 1
    pao 2
    kumar 2
    parker 2
    9 rows selected.
    QUERY 2:
    with main as(select 1 id,'john' name,null mgrid from dual union all
    select 2 id,'michael' name,null mgrid from dual union all
    select 3 id,'peter' name,null mgrid from dual union all
    select 4 id,'henry' name,1 mgrid from dual union all
    select 5 id,'nick' name,2 mgrid from dual union all
    select 6 id,'pao' name,3 mgrid from dual union all
    select 7 id,'kumar' name,3 mgrid from dual union all
    select 8 id,'parker' name,3 mgrid from dual union all
    select 9 id,'mike' name,5 mgrid from dual),
    /*select lpad(' ',2*(level-1))||name name,level from main start with mgrid is null connect by prior id=mgrid;*/
    secmain (id,name,mgrid,hierlevel) as(select id,name,mgrid,1 hierlevel from main where mgrid is null
    union all
    select m.id,m.name,m.mgrid,sm.hierlevel+1 from main m join secmain sm on(m.mgrid=sm.id))
    cycle id set is_cycle to 1 default 0
    select lpad(' ',2*(hierlevel-1))||name name,hierlevel from secmain;
    OUTPUT :
    NAME HIERLEVEL
    john 1
    michael 1
    peter 1
    henry 2
    nick 2
    parker 2
    kumar 2
    pao 2
    mike 3
    9 rows selected.

    Hi,
    What's wrong with Query 1? If it's producing the results you want, then why not use it?
    One of the nice features of CONNECT BY is that the output is automatically presented in hierachical order. The only way I know of to get the results of a recursive WITH clause in any kind or order is to do it yourself. Here's one way:
    WITH       secmain (id, name, mgrid, hierlevel, path)     AS
         SELECT  id
         ,     name
         ,     mgrid
         ,     1               AS hierlevel
         ,     RPAD (name, 10)          AS path          -- Assuming name is never longer than 10
         FROM      main
         WHERE      mgrid     IS NULL
        UNION ALL
             SELECT     m.id
         ,     m.name
         ,     m.mgrid
         ,     sm.hierlevel + 1
         ,     sm.path || RPAD (name, 10)
         FROM     main      m
         JOIN     secmain  sm  ON   (m.mgrid     = sm.id)
         CYCLE     id     -- Why do you need this if CONNECT BY NOCYCLE wasn't needed in Query 1?
         SET      is_cycle     TO 1
         DEFAULT 0
    SELECT        lpad ( ' '
                , 2 * (hierlevel - 1)
                ) || name                 AS name
    ,       hierlevel
    FROM        secmain
    ORDER BY  path
    ;Sorry, I don't have an Oracle 11.2 database right now, so I can't test it.
    Edited by: Frank Kulash on Nov 23, 2011 9:15 AM
    I didn't know about the SEARCH clause, Use Dom's solution, above.

Maybe you are looking for

  • IPod Touch 1g not recognized in Windows and iTunes

    Hi all i have a old iPod Touch 1g at home. the problem is that the device is death. I can hold Home and Pwr button for a long time but nothing happens. Even when i connect it to a Pc running XP, Windows 7 or a Mac the screen stays black and no error

  • Font unavailable in script

    I have written the following script to generate a font index in an InDesign document: // Generate new document var doc = app.documents.add(); var frm = doc.pages[0].textFrames.add(); var w = doc.documentPreferences.pageWidth; var h = doc.documentPref

  • Acrobat XI 11.0.06 Addins not showing in Office 2013

    I've installed Acrobat XI Standard 32 bit on a Windows 7 64 bit machine with Office 2013 32 bit.  The Acobat addins do not appear in the "Options>Addins" in any of the Office apps. I've installed the latest updates for Acrobat still no luck. Repaired

  • About bw report

    hi to all, i m very new to bw. i want to open the stock details of last month,as per plant wise. what is tcode, tell me what is the path? giv reply asap. thanks n regards murty

  • How to find out Standard Functionalities in ECC 6.0

    Hi Friends, Can any one of you, please tell me as how to find out SAP Standard Functionalities of a particular Module in SAP-HCM (Eg: SAP-HR - PA module in ECC 6.0). Thank you in advance and in anticipation of your reply.