Group by - sub query

A table has three columns - id (primary key), categoryID (numeric) and amount (numeric).
The goal is to provide a query that would show categoryID and sum of amounts within that category where categoryID is an odd number and sum of amounts is greater than 100,000

By category within id:
SELECT  id,
        categoryID,
        SUM(amount)
  FROM  tbl
  WHERE MOD(categoryID,2) = 1
  GROUP BY id,
           categoryID
  HAVING SUM(amount) > 100000
/By category across all ids:
SELECT  categoryID,
        SUM(amount)
  FROM  tbl
  WHERE MOD(categoryID,2) = 1
  GROUP BY categoryID
  HAVING SUM(amount) > 100000
/SY.
Edited by: Solomon Yakobson on Nov 15, 2009 8:02 AM

Similar Messages

  • ORA-01427:single-row sub query returns more than one row (group by)

    Hello every one, I am very new to this field , and Right now I am working with this sql, where BEG_BAL_WKST,WKST_RECEIVED_NUM,WKST_PROCESSED_NUM,WKST_CANCELED_NUM are needs to be grouped by,but I am getting the "single-row sub query returns more than one row".
    This is the query I am using in my source qualifier:
    select
    SUM(tmp.WIP_TO_BILL_LOC_AMT) AS WIP_TO_BILL_LOC_AMT,
    sum(tmp.REALIZATION_LOC_AMT) AS REALIZATION_LOC_AMT,
    SUM(tmp.NEG_REAL_LOC_AMT) AS NEG_REAL_LOC_AMT,
    sum(tmp.POS_REAL_LOC_AMT) AS POS_REAL_LOC_AMT,
    sum(tmp.BILL_IN_ADVANCE_LOC_AMT) AS BILL_IN_ADVANCE_LOC_AMT,
    sum(tmp.CARRY_FORWARD_LOC_AMT) AS CARRY_FORWARD_LOC_AMT,
    sum(tmp.BILL_TO_CLIENT_LOC_AMT) AS BILL_TO_CLIENT_LOC_AMT,
    sum(tmp.REMAIN_WIP_TO_BILL_LOC_AMT) REMAIN_WIP_TO_BILL_LOC_AMT,
    sum(tmp.AR_INV_AMT) AS AR_INV_AMT,
    sum(tmp.AR_TAX_AMT) AS AR_TAX_AMT,
    tmp.BEG_BAL_WKST_NUM AS BEG_BAL_WKST_NUM,
    tmp.WKST_RECEIVED_NUM AS WKST_RECEIVED_NUM,
    tmp.WKST_PROCESSED_NUM AS WKST_PROCESSED_NUM,
    tmp.WKST_CANCELED_NUM AS WKST_CANCELED_NUM,
    tmp.DURATION AS DURATION,
    tmp.NUM_DAYS AS NUM_DAYS,
    tmp.NUM_HOURS AS NUM_HOURS,
    tmp.NUM_MINUTES AS NUM_MINUTES,
    tmp.NUM_SECONDS AS NUM_SECONDS,
    tmp.LEAD_PROJECT_OFFICE_CODE AS LEAD_PROJECT_OFFICE_CODE,
    tmp.LEAD_PROJECT_TEAM_CODE AS LEAD_PROJECT_TEAM_CODE,
    tmp.ORG_ID AS ORG_ID,
    tmp.RPT_DATE AS RPT_DATE,
    tmp.RPT_DATE_WID AS RPT_DATE_WID,
    tmp.LOCAL_CURR_CODE AS LOCAL_CURR_CODE,
    tmp.USD_EXCH_RATE AS USD_EXCH_RATE,
    tmp.EUR_EXCH_RATE AS EUR_EXCH_RATE,
    tmp.GBP_EXCH_RATE AS GBP_EXCH_RATE
    from(
    SELECT
    WIP_TO_BILL_LOC_AMT as WIP_TO_BILL_LOC_AMT ,
    REALIZATION_LOC_AMT AS REALIZATION_LOC_AMT,
    NEG_REAL_LOC_AMT AS NEG_REAL_LOC_AMT ,
    POS_REAL_LOC_AMT AS POS_REAL_LOC_AMT,
    BILL_IN_ADVANCE_LOC_AMT AS BILL_IN_ADVANCE_LOC_AMT ,
    CARRY_FORWARD_loc_AMT AS CARRY_FORWARD_LOC_AMT,
    bill_to_client_LOC_AMT AS BILL_TO_CLIENT_LOC_AMT ,
    REMAIN_WIP_TO_BILL_LOC_AMT AS REMAIN_WIP_TO_BILL_LOC_AMT,
    AR_inv_AMT AS AR_INV_AMT,
    ar_tax_amt AS AR_TAX_AMT,
    (SELECT count(distinct(RPAD(INTEGRATION_ID,32)))
    FROM wc_twfs_olb_invoice_history_f
    WHERE ((inv_status_type='FIN'AND inv_status_code NOT IN ('COMPLETE','PROCESSED'))
    OR (inv_status_type='WS' AND inv_status_code NOT IN ('PRC'))) --COMPLETED
    AND to_char((sysdate-5),'YYYYMMDD') between to_char(status_start_dt,'YYYYMMDD') and to_char(status_end_dt,'YYYYMMDD')group by rpad(integration_id,32)) AS BEG_BAL_WKST_NUM ,
    (SELECT count(distinct(RPAD(INTEGRATION_ID,32)))
    FROM wc_twfs_olb_invoice_history_f
    WHERE (inv_status_code='NEW')
    AND to_char((sysdate-4),'YYYYMMDD') between to_char(status_start_dt,'YYYYMMDD') and to_char(status_end_dt,'YYYYMMDD')group by rpad(integration_id,32))AS WKST_RECEIVED_NUM ,
    (SELECT count(distinct(RPAD(INTEGRATION_ID,32)))
    FROM wc_twfs_olb_invoice_history_f
    WHERE ((inv_status_type='FIN' and inv_status_code IN ('COMPLETE','PROCESSED'))
    OR (inv_status_type='WS' AND inv_status_code IN ('PRC'))) --COMPLETED
    AND to_char((sysdate-4),'YYYYMMDD') between to_char((status_start_dt),'YYYYMMDD') and to_char((status_end_dt),'YYYYMMDD')group by rpad(integration_id,32))AS WKST_PROCESSED_NUM ,
    (SELECT count(distinct(RPAD(INTEGRATION_ID,32)))
    FROM wc_twfs_olb_invoice_history_f
    WHERE (inv_status_type='FIN' AND inv_status_code='CANCELLED')
    AND to_char((sysdate-4),'YYYYMMDD') between to_char((status_start_dt),'YYYYMMDD') and to_char((status_end_dt),'YYYYMMDD')group by rpad(integration_id,32)) AS WKST_CANCELED_NUM,
    DURATION AS DURATION,
    NUM_DAYS AS NUM_DAYS,
    NUM_HOURS AS NUM_HOURS,
    NUM_MINUTES AS NUM_MINUTES,
    NUM_SECONDS AS NUM_SECONDS,
    lead_project_office_code AS LEAD_PROJECT_OFFICE_CODE,
    lead_project_team_code AS LEAD_PROJECT_TEAM_CODE,
    org_id AS ORG_ID,
    trunc(sysdate-1) AS RPT_DATE,
    to_char((sysdate-1),'YYYYMMDD') AS RPT_DATE_WID,
    --last_day(a.report_date) mth_end_dt,
    LOC_CURR_CODE AS LOCAL_CURR_CODE,
    usd_exch_rate AS USD_EXCH_RATE,
    eur_exch_rate AS EUR_EXCH_RATE,
    gbp_exch_rate AS GBP_EXCH_RATE
    FROM Wc_twfs_olb_invoice_history_f
    Where
    RPT_DT_MCAL_PERIOD_WID =(select max(RPT_DT_MCAL_PERIOD_WID)from Wc_twfs_olb_invoice_history_f))tmp
    group by BEG_BAL_WKST_NUM,WKST_RECEIVED_NUM,WKST_PROCESSED_NUM,WKST_CANCELED_NUM,DURATION,NUM_DAYS,NUM_HOURS,NUM_MINUTES,NUM_SECONDS,
    LEAD_PROJECT_OFFICE_CODE,LEAD_PROJECT_TEAM_CODE,ORG_ID,RPT_DATE,RPT_DATE_WID,
    LOCAL_CURR_CODE,USD_EXCH_RATE,EUR_EXCH_RATE,GBP_EXCH_RATE;
    Can you please suggest me what to do next, and what would be the solution to this.
    Thanks a lot in advance. please show me some direction.

    you may want to change it something like
    SELECT SUM(Wip_To_Bill_Loc_Amt) AS Wip_To_Bill_Loc_Amt,
           SUM(Realization_Loc_Amt) AS Realization_Loc_Amt,
           SUM(Neg_Real_Loc_Amt) AS Neg_Real_Loc_Amt,
           SUM(Pos_Real_Loc_Amt) AS Pos_Real_Loc_Amt,
           SUM(Bill_In_Advance_Loc_Amt) AS Bill_In_Advance_Loc_Amt,
           SUM(Carry_Forward_Loc_Amt) AS Carry_Forward_Loc_Amt,
           SUM(Bill_To_Client_Loc_Amt) AS Bill_To_Client_Loc_Amt,
           SUM(Remain_Wip_To_Bill_Loc_Amt) AS Remain_Wip_To_Bill_Loc_Amt,
           SUM(Ar_Inv_Amt) AS Ar_Inv_Amt,
           SUM(Ar_Tax_Amt) AS Ar_Tax_Amt,
           COUNT(DISTINCT CASE
                   WHEN ((Inv_Status_Type = 'FIN' AND
                        Inv_Status_Code NOT IN ('COMPLETE', 'PROCESSED')) OR
                        (Inv_Status_Type = 'WS' AND Inv_Status_Code NOT IN ('PRC'))) --COMPLETED
                        AND To_Char((SYSDATE - 5), 'YYYYMMDD') BETWEEN
                        To_Char(Status_Start_Dt, 'YYYYMMDD') AND
                        To_Char(Status_End_Dt, 'YYYYMMDD') THEN
                    Rpad(Integration_Id, 32)
                 END) AS Beg_Bal_Wkst_Num,
           /*(SELECT COUNT(DISTINCT(Rpad(Integration_Id, 32)))
              FROM Wc_Twfs_Olb_Invoice_History_f
             WHERE ((Inv_Status_Type = 'FIN' AND
                   Inv_Status_Code NOT IN ('COMPLETE', 'PROCESSED')) OR
                   (Inv_Status_Type = 'WS' AND Inv_Status_Code NOT IN ('PRC'))) --COMPLETED
               AND To_Char((SYSDATE - 5), 'YYYYMMDD') BETWEEN
                   To_Char(Status_Start_Dt, 'YYYYMMDD') AND
                   To_Char(Status_End_Dt, 'YYYYMMDD')
             GROUP BY Rpad(Integration_Id, 32)) AS Beg_Bal_Wkst_Num,
           (SELECT COUNT(DISTINCT(Rpad(Integration_Id, 32)))
              FROM Wc_Twfs_Olb_Invoice_History_f
             WHERE (Inv_Status_Code = 'NEW')
               AND To_Char((SYSDATE - 4), 'YYYYMMDD') BETWEEN
                   To_Char(Status_Start_Dt, 'YYYYMMDD') AND
                   To_Char(Status_End_Dt, 'YYYYMMDD')
             GROUP BY Rpad(Integration_Id, 32)) AS Wkst_Received_Num,
           (SELECT COUNT(DISTINCT(Rpad(Integration_Id, 32)))
              FROM Wc_Twfs_Olb_Invoice_History_f
             WHERE ((Inv_Status_Type = 'FIN' AND
                   Inv_Status_Code IN ('COMPLETE', 'PROCESSED')) OR
                   (Inv_Status_Type = 'WS' AND Inv_Status_Code IN ('PRC'))) --COMPLETED
               AND To_Char((SYSDATE - 4), 'YYYYMMDD') BETWEEN
                   To_Char((Status_Start_Dt), 'YYYYMMDD') AND
                   To_Char((Status_End_Dt), 'YYYYMMDD')
             GROUP BY Rpad(Integration_Id, 32)) AS Wkst_Processed_Num,
           (SELECT COUNT(DISTINCT(Rpad(Integration_Id, 32)))
              FROM Wc_Twfs_Olb_Invoice_History_f
             WHERE (Inv_Status_Type = 'FIN' AND Inv_Status_Code = 'CANCELLED')
               AND To_Char((SYSDATE - 4), 'YYYYMMDD') BETWEEN
                   To_Char((Status_Start_Dt), 'YYYYMMDD') AND
                   To_Char((Status_End_Dt), 'YYYYMMDD')
             GROUP BY Rpad(Integration_Id, 32)) AS Wkst_Canceled_Num,*/
           Duration AS Duration,
           Num_Days AS Num_Days,
           Num_Hours AS Num_Hours,
           Num_Minutes AS Num_Minutes,
           Num_Seconds AS Num_Seconds,
           Lead_Project_Office_Code AS Lead_Project_Office_Code,
           Lead_Project_Team_Code AS Lead_Project_Team_Code,
           Org_Id AS Org_Id,
           Trunc(SYSDATE - 1) AS Rpt_Date,
           To_Char((SYSDATE - 1), 'YYYYMMDD') AS Rpt_Date_Wid,
           --last_day(a.report_date) mth_end_dt,
           Loc_Curr_Code AS Local_Curr_Code,
           Usd_Exch_Rate AS Usd_Exch_Rate,
           Eur_Exch_Rate AS Eur_Exch_Rate,
           Gbp_Exch_Rate AS Gbp_Exch_Rate
      FROM Wc_Twfs_Olb_Invoice_History_f
    WHERE Rpt_Dt_Mcal_Period_Wid =
           (SELECT MAX(Rpt_Dt_Mcal_Period_Wid)
              FROM Wc_Twfs_Olb_Invoice_History_f)
    GROUP BY Beg_Bal_Wkst_Num,
              Wkst_Received_Num,
              Wkst_Processed_Num,
              Wkst_Canceled_Num,
              Duration,
              Num_Days,
              Num_Hours,
              Num_Minutes,
              Num_Seconds,
              Lead_Project_Office_Code,
              Lead_Project_Team_Code,
              Org_Id,
              Rpt_Date,
              Rpt_Date_Wid,
              Local_Curr_Code,
              Usd_Exch_Rate,
              Eur_Exch_Rate,
              Gbp_Exch_Rate;Edited by: 986006 on Mar 4, 2013 1:08 PM

  • 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.

  • 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

  • GROUP and MAX Query

    Hi
    I have two tables that store following information
    CREATE TABLE T_FEED (FEED_ID NUMBER, GRP_NUM NUMBER);
    CREATE TABLE T_FEED_RCV (FEED_ID NUMBER, RCV_DT DATE);
    INSERT INTO T_FEED VALUES (1, 1);
    INSERT INTO T_FEED VALUES (2, 1);
    INSERT INTO T_FEED VALUES (3, 2);
    INSERT INTO T_FEED VALUES (4, NULL);
    INSERT INTO T_FEED VALUES (5, NULL);
    INSERT INTO T_FEED_RCV VALUES (2, '1-MAY-2009');
    INSERT INTO T_FEED_RCV VALUES (3, '1-FEB-2009');
    INSERT INTO T_FEED_RCV VALUES (4, '12-MAY-2009');
    COMMIT;
    I join these tables using the following query to return all the feeds and check when each feed was received:
    SELECT
    F.FEED_ID,
    F.GRP_NUM,
    FR.RCV_DT
    FROM T_FEED F
    LEFT OUTER JOIN T_FEED_RCV FR
    ON F.FEED_ID = FR.FEED_ID
    ORDER BY GRP_NUM, RCV_DT DESC;
    Output
    Line: ----------
    FEED_ID     GRP_NUM     RCV_DT
    1     1     
    2     1     5/1/2009
    3     2     2/1/2009
    5          
    4          5/12/2009
    Actually I want the maximum date of when we received the feed. Grp_Num tells which feeds are grouped together. NULL grp_num means they are not grouped so treat them as individual group. In the example - Feeds 1 and 2 are in one group and any one of the feed is required. Feed 3, 4 and 5 are individual groups and all the three are required.
    I need a single query that should return the maximum date for the feeds. For the example the result should be NULL because.. out of feed 1 and 2 the max date is 5/1/2009. For feed 3 the max date is 2/1/2009, for feed 4 it is 5/12/2009 and for feed 4 it is NULL. Since one of the required feed is null so the results should be null.
    DELETE FROM T_FEED;
    DELETE FROM T_FEED_RCV;
    COMMIT;
    INSERT INTO T_FEED VALUES (1, 1);
    INSERT INTO T_FEED VALUES (2, 1);
    INSERT INTO T_FEED VALUES (3, NULL);
    INSERT INTO T_FEED VALUES (4, NULL);
    INSERT INTO T_FEED_RCV VALUES (2, '1-MAY-2009');
    INSERT INTO T_FEED_RCV VALUES (3, '1-FEB-2009');
    INSERT INTO T_FEED_RCV VALUES (4, '12-MAY-2009');
    COMMIT;
    For above inserts, the result should be for feed 1 and 2 - 5/1/2009, feed 3 - 2/1/2009 and feed 4 - 5/12/2009. So the max of these dates is 5/12/2009.
    I tried using MAX function grouped by GRP_NUM and also tried using DENSE_RANK but unable to resolve the issue. I am not sure how can I use the same query to return - not null value for same group and null (if any) for those that doesn't belong to any group. Appreciate if anyone can help me..

    Hi,
    Kuul13 wrote:
    Thanks Frank!
    Appreciate your time and solution. I tweaked your earlier solution which was more cleaner and simple and built the following query to resolve the prblem.
    SELECT * FROM (
    SELECT NVL (F.GRP_NUM, F.CARR_ID || F.FEED_ID || TO_CHAR(EFF_DT, 'MMDDYYYY')) AS GRP_ID
    ,MAX (FR.RCV_DT) AS MAX_DT
    FROM T_FEED F
    LEFT OUTER JOIN T_FEED_RCV FR ON F.FEED_ID = FR.FEED_ID
    GROUP BY NVL (F.GRP_NUM, F.CARR_ID || F.FEED_ID || TO_CHAR(EFF_DT, 'MMDDYYYY'))
    ORDER BY MAX_DT DESC NULLS FIRST)
    WHERE ROWNUM=1;
    I hope there are no hidden issues with this query than the later one provided by you.Actually, I can see 4 issues with this. I admit that some of them are unlikely, but why take any chances?
    (1) The first argument to NVL is a NUMBER, the second (being the result of ||) is a VARCHAR2. That means one of them will be implicitly converted to the type of the other. This is just the kind of thing that behaves differently in different versions or Oracle, so it may work fine for a year or two, and then, when you change to another version, mysteriously quit wiorking. When you have to convert from one type of data to another, always do an explicit conversion, using TO_CHAR (for example).
    (2)
    F.CARR_ID || F.FEED_ID || TO_CHAR(EFF_DT, 'MMDDYYYY)'will produce a key like '123405202009'. grp_num is a NUMBER with no restriction on the number of digits, so it could conceivably be 123405202009. The made-up grp_ids must never be the same any real grp_num.
    (3) The combination (carr_id, feed_id, eff_dt) is unique, but using TO_CHAR(EFF_DT, 'MMDDYYYY) assumes that the combination (carr_id, feed_id, TRUNC (eff_dt)) is unique. Even if eff_dt is always entered as (say) midnight (00:00:00) now, you may decide to start using the time of day sometime in the future. What are the chances that you'll remember to change this query when you do? Not very likely. If multiple rows from the same day are relatively rare, this is the kind of error that could go on for months before you even realize that there is an error.
    (4) Say you have this data in t_feed:
    carr_id      feed_id  eff_dt       grp_num
    1        234      20-May-2009  NULL
    12       34       20-May-2009  NULL
    123      4        20-May-2009  NULLAll of these rows will produce the same grp_id: 123405202009.
    Using NVL, as you are doing, allows you to get by with just one sub-query, which is nice.
    You can do that and still address all the problems above:
    SELECT  *
    FROM     (
         SELECT  NVL2 ( F.GRP_NUM
                   , 'A' || TO_CHAR (f.grp_num)
                   , 'B' || TO_CHAR (f.carr_id) || ':' ||
                                TO_CHAR (f.feed_id) || ':' ||
                                TO_CHAR ( f.eff_dt
                                            , 'MMDDYYYYHH24MISS'
                   ) AS grp_id
         ,     MAX (FR.RCV_DT) AS MAX_DT
         FROM               T_FEED      F
         LEFT OUTER JOIN  T_FEED_RCV  FR        ON  F.FEED_ID = FR.FEED_ID
         GROUP BY  NVL2 ( F.GRP_NUM
                     , 'A' || TO_CHAR (f.grp_num)
                     , 'B' || TO_CHAR (f.carr_id) || ':' ||
                                     TO_CHAR (f.feed_id) || ':' ||
                                     TO_CHAR ( f.eff_dt
                                                 , 'MMDDYYYYHH24MISS'
         ORDER BY  MAX_DT   DESC   NULLS FIRST
    WHERE      ROWNUM = 1;I would still use two sub-queries, adding one to compute grp_id, so we don't have to repeat the NVL2 expression. I would also use a WITH clause rather than in-line views.
    Do you find it easier to read the query above, or the simpler query you posted in your last message?
    Please make things easy on yourself and the people who want to help you. Always format your code so that the way the code looks on the screen makes it clear what the code is doing.
    In particular, the formatting should make clear
    (a) where each clause (SELECT, FROM, WHERE, ...) of each query begins
    (b) where sub-queries begin and end
    (c) what each argument to functions is
    (d) the scope of parentheses
    When you post formatted text on this site, type these 6 characters:
    before and after the formatted text, to preserve spacing.
    The way you post the DDL (CREATE TABLE ...)  and DML (INSERT ...) statements is great: I wish more people were as helpful as you.
    There's no need to format the DDL and DML.  (If you want to, then go ahead: it does help a little.)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Doubt in sub-query

    I have a doubt with the use of sub-queries. I am using a query like as below & it is giving me expected result:-
    SELECT ISS.item_type_id,count(1) + (select sum(invoiced_qty) from ppbs_invoice_detail where
    trunc(created_date) between '01-jul-05' and '04-jul-05' and item_type_id=ISS.item_type_id) qty
    FROM ppbs_INV_SIM_SERIAL ISS
    WHERE INSTR('ROAAIT',STATUS)>0
    AND INSTR('NU0NU1NU2NU3SC0',CITY_CODE) =0
    and ISS.item_type_id in ('SM17')
    group by ISS.item_type_id --
    I will re-write above query & i have been using queries like :-
    SELECT ISS.item_type_id,count(1) qty
    FROM ppbs_INV_SIM_SERIAL ISS
    WHERE INSTR('ROAAIT',STATUS)>0
    AND INSTR('NU0NU1NU2NU3SC0',CITY_CODE) =0
    and ISS.item_type_id in ('SM17') and item_type_id in
    (select item_type_id from ppbs_invoice_detail where
    trunc(created_date) between '01-jul-05' and '04-jul-05' and item_type_id=ISS.item_type_id)
    group by ISS.item_type_id
    my doubt here is that the sub-query in the first query is coming before i use the table 'ppbs_inv_sim_serial ISS' whereas in the second query, the table use 'ppbs_inv_sim_serial ISS' is coming before the sub-query use. I have been using queries where table name is defined before the sub-query.
    I hope, my question is clear. Please help in solving the doubt.
    Regards.

    I don't see a problem with the table aliasing that you seem to doubt, but your first query won't run. I boiled the thing down to basics: SQL>create table t1 (one number, val_1 number );
    Table created.
    SQL>create table t2 (one number, val_2 number );
    Table created.
    SQL>insert into t1 values (1,1);
    1 row created.
    SQL>insert into t2 values (1,2);
    1 row created.
    SQL>select a.one, count(1) + ( select sum(val_2) from t2 where t2.one = a.one) qty
      2  from  t1 a
      3  group by one;
    select a.one, count(1) + ( select sum(val_2) from t2 where t2.one = a.one) qty
    ERROR at line 1:
    ORA-00979: not a GROUP BY expression
    SQL>
    SQL>select a.one, count(1) qty
      2  from   t1 a
      3  where  a.one in ( select one from t2 where one = a.one)
      4  group by one;
           ONE        QTY
             1          1It's superfluous to "where a.one in ( select.. where = a.one) but that's your code basically. I would just do "="

  • 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

  • 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

  • How to write multi row sub query with the row containing range of values?

    Hi all,
    I have to include a column which contains weight ranges and it should come fom table called "report_range_parameters"
    The following query will reutrn those weight ranges.
    select report_parameter_min_value || ' -> ' || report_parameter_max_value
              from report_range_parameters
             WHERE report_range_parameters.report_parameter_id = 2359
               and report_range_parameters.report_parameter_group = 'GVW_GROUP'
               and report_range_parameters.report_parameter_name  = 'GVW_NAME'
                        The below query should return the values group by those weight ranges.
    How could I write that sub query?
    select   SUM(NVL("Class 0", 0)) "Class 0"  ,
                SUM(NVL("Class 1", 0)) "Class 1"  ,
                SUM(NVL("Class 2", 0)) "Class 2"  ,
                SUM(NVL(" ", 0)) "Total"
         FROM (
                 SELECT report_data.bin_start_date_time start_date_time,
                        SUM(DECODE(report_data.gvw, 0, report_data.gvw_count, 0)) "Class 0" ,
                        SUM(DECODE(report_data.gvw, 1, report_data.gvw_count, 0)) "Class 1" ,
                        SUM(DECODE(report_data.gvw, 2, report_data.gvw_count, 0)) "Class 2" ,
                        SUM(NVL(report_data.gvw_count, 0)) " "
                  FROM report_data
                 GROUP BY report_data.bin_start_date_time
              ) results
       RIGHT OUTER JOIN tmp_bin_periods
                     ON results.start_date_time >= tmp_bin_periods.bin_start_date_time
                    AND results.start_date_time <  tmp_bin_periods.bin_end_date_time
               GROUP BY tmp_bin_periods.bin_start_date_time,
                        tmp_bin_periods.bin_end_date_time Thanks.
    Edited by: user10641405 on Jun 15, 2009 3:14 PM
    Edited by: user10641405 on Jun 15, 2009 3:17 PM

    Hi,
    Assuming the following 4 things:
    (1) report_range_parameters contains data like this, from your [previous thread|http://forums.oracle.com/forums/message.jspa?messageID=3541079#3541079]
    id  group      name         min_value      max_value
    1   gvw_group  gvw_name      0              5
    2   gvw_group  gvw_name      5              10
    3   gvw_group  gvw_name     10              15(2) max_value is actually outside the range (that is, a value of exactly 5.000 is counted in the '5->10' range, not the '0->5' range)
    (3) the range has to match some column x that is in one of the tables in your main query
    (4) You want to add that column x to the GROUP BY clause
    then you shopuld do somehting like this:
    select   SUM(NVL("Class 0", 0)) "Class 0"  ,
                SUM(NVL("Class 1", 0)) "Class 1"  ,
                SUM(NVL("Class 2", 0)) "Class 2"  ,
                SUM(NVL(" ", 0)) "Total"
    ,         report_parameter_min_value || ' -> ' || report_parameter_max_value     AS weight_range          -- New
         FROM (
                 SELECT report_data.bin_start_date_time start_date_time,
                        SUM(DECODE(report_data.gvw, 0, report_data.gvw_count, 0)) "Class 0" ,
                        SUM(DECODE(report_data.gvw, 1, report_data.gvw_count, 0)) "Class 1" ,
                        SUM(DECODE(report_data.gvw, 2, report_data.gvw_count, 0)) "Class 2" ,
                        SUM(NVL(report_data.gvw_count, 0)) " "
                  FROM report_data
                 GROUP BY report_data.bin_start_date_time
              ) results
       RIGHT OUTER JOIN tmp_bin_periods
                     ON results.start_date_time >= tmp_bin_periods.bin_start_date_time
                    AND results.start_date_time <  tmp_bin_periods.bin_end_date_time
       LEFT OUTER JOIN  report_range_parameters                                        -- New
                    ON  x >= report_parameter_min_value                                    -- New
              AND x <  report_parameter_max_value                                   -- New
                    AND report_range_parameters.report_parameter_id = 2359                         -- New
                    and report_range_parameters.report_parameter_group = 'GVW_GROUP'               -- New
                    and report_range_parameters.report_parameter_name  = 'GVW_NAME'                    -- New
               GROUP BY tmp_bin_periods.bin_start_date_time,
                        tmp_bin_periods.bin_end_date_time
                  , x                                                       -- New

  • Weird prob with sub query

    Hello All,
    I am having trouble with the code. I am using a subquery in the select statment and the same in the where clause(2nd sq in the select which populates on_hand column). I have highlighted the sub query as shown below. The code runs fine when i comment the subquery in select, which gets "sub_inv" column value(3rd subquery in the select). if i include it then i get ora-01427 error though neither of the sub queries return multiple rows.
    Please let me know where i am going wrong.
    select ms.organization_id, ms.segment1,ms.description,
    ms.planner_code,pl.closed_code,ploc.quantity - ploc.quantity_received - ploc.quantity_cancelled qty_rem,
    (select full_name from
              per_all_people_f p,
              inv.mtl_planners mp
              where
              ms.planner_code = mp.planner_code
              and mp.employee_id = p.person_id
              and mp.organization_id = ms.organization_id) planner_name,
    min_minmax_quantity, max_minmax_quantity,
    /***2nd sq***/
    (select sum( oh.transaction_quantity)
                   from mtl_onhand_quantities_detail oh
                   where ms.inventory_item_id = oh.inventory_item_id
                   and ms.organization_id = oh.organization_id
                   ) on_hand,
    /***3rd sq***/
    (select oh.subinventory_code
                   from mtl_onhand_quantities_detail oh
                   where ms.inventory_item_id = oh.inventory_item_id
                   and ms.organization_id = oh.organization_id ) sub_inv,
    ph.segment1, pl.line_num, ploc.shipment_num,
    nvl((select vendor_name from po_vendors where vendor_id = ph.vendor_id),'NONE') vendor_name,
    pr.release_num,
    PL.PO_LINE_ID,
    PH.PO_HEADER_ID
    from
    inv.mtl_system_items_b ms,
    po.po_line_locations_all ploc,
    po_lines_all pl,
    po_headers_all ph,
    po.po_releases_all pr
    where 1=1
    and ms.inventory_item_id = pl.item_id(+)
    and pl.po_line_id = ploc.po_line_id
    and pl.po_header_id = ph.po_header_id
    and ploc.po_release_id = pr.po_release_id(+)
    and ploc.quantity - (ploc.quantity_received + ploc.quantity_cancelled) > 0
    and nvl(pl.closed_code (+), 'OPEN')= 'OPEN'
    AND NVL(PLOC.CLOSED_CODE,'OPEN') = 'OPEN'
    ---and ms.organization_id = 43
    --and ms.inventory_item_id = 708
    and max_minmax_quantity is not null
    and min_minmax_quantity is not null
    and (select sum( oh.transaction_quantity)
                   from mtl_onhand_quantities_detail oh
                   where ms.inventory_item_id =oh.inventory_item_id
                   and ms.organization_id = oh.organization_id
                   ) is not null

    >
    shown below. The code runs fine when i comment the
    subquery in select, which gets "sub_inv" column
    value(3rd subquery in the select). if i include it
    then i get ora-01427 error though neither of the sub
    queries return multiple rows.
    Please let me know where i am going wrong. Are you sure about this ?
    I believe this is Oracle apps tables, and if it's true one item in one org can have multiple rows with the same subinventory_code in mtl_onhand_quantities_detail table.
    Run the query below to check and see if it return any rows :
    select inventory_item_id, organization_id,count(subinventory_code)
    from mtl_onhand_quantities_detail
    group by inventory_item_id,organization_id
    having count(subinventory_code) > 1

  • Filter query with sub query using Dropdown box

    Dear Community,
    I have 2 queries
    1. Main Query with 2 fields:  Project | Project value
    2. Sub Query with 2 fields:  Project group | Project
    Project group can be belonging to number of projects and project can be belong to number of project group (Many to Many).
    My customer wants the main query will open without any filtering.
    When I choose project group from WAD dropdown box, the main query will filtering all the projects that belong to the project group.
    I create WAD; define dropdown box as sub query, and Analysis as main query.
    In the dropdown box I choose "data binding" char and create command "set selection state by binding" (project to project) but it doesnu2019t work. 
    I also try to do this by Replacement Path in the main query, but the variable requires the attribute will be ready for input.
    Thanks a lot
    Yaniv

    I am not sure about your comments on replacement path variable. Without having tried it, here is what I would have attempted:
    The main query needs to use a replacement path variable for Project that is replaced by the results of the sub-query. Sub-query would have a regular input variable for project group. (as a quick test, if you had one analysis item for main query with variable input enabled, it should prompt you to enter Project group).
    Now the drop-down needs to be associated with a javascript function. The javascript function needs to implement command "Set variable state" for the main query data provider to selected value of the drop-down.
    The drop-down should be associated with the sub-query data provider, just used to populate the list of values in drop-down.

  • 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

  • Sub query filter may not reference current Report

    Hi,
    I've 2 reports, i'm calling one from the another report by navigate methode(Column Propertives--> Value-->Navigate). 2nd report is having narrative veiw in title of the report .
    Getting Error:
    Sub query filter may not reference current Report

    hi,
    have u seen this ?
    http://siebel.ittoolbox.com/groups/technical-functional/siebel-analytics-l/issue-with-drill-down-1710714
    thanks,
    Saichand.v

  • Help on Converting inerr query to sub query

    Hi Guys,
    This query is written in inner join, can any one try to write using sub query.
    SELECT B.CNO
    FROM CUSTEN A
    INNER JOIN ORDS B
    ON A.CNO = B.CNO
    AND A.PRNO = B.PRNO
    INNER JOIN ORDI C
    ON B.ORDNO = C.ORDNO
    INNER JOIN PRD D
    ON C.PRNO = D.PRNO
    WHERE B.STS = 'COM'
    AND B.LMD >= A.LMD
    GROUP BY B.CSTNO, C.PRNO
    HAVING COUNT(B.ORDNO) > 1
    Thanks in advance!
    Regards,
    LKRao
    Edited by: kolipaka on Sep 18, 2012 6:37 PM
    Edited by: kolipaka on Sep 18, 2012 6:38 PM

    Hi,
    kolipaka wrote:
    Hi Guys,
    This query is written in inner join, can any one try to write using sub query. Why?
    We don't know your requirements, so we can't be sure if any solution we might think of meets your requirements.
    ... GROUP BY B.CSTNO, C.PRNOIf you really need to GROUP BY columns from different tables, then you almost certainly want to join those tables. You might be able to get the results you want with a scalar sub-query instead of a join, but that's needlessly complicated.
    You said that what you posted is just a sub-query of some other query. Perhaps the solution involves making changes in that query, too. Post the complete query, CREATE TABLE and INSERT statments for a little sample data, the results you want from that data, and an explanation of how you get those results from that data. Say which columns are unique (expecially the columns used in the join conditions); that could be important.

Maybe you are looking for

  • Downloads to sd card

    Hello, My phone is running really slow after a few app downloads. I read I should archive the apps (to sd-card), but since I have downloaded latest version of App World I cant find the 'archive' button no more in the menu of the applications. Could s

  • HT201269 How can I transfer photo's from one ipad to another. I believe I can't use iCloud as the photo's were originally synced to the ipad via iTunes's

    I have some photo's on an ipad 2 that were put on there through syncing on iTunes,  I would like them to be placed on my new ipad. I understand that I can't use iCloud ?  Just to point out u no longer own the desk top pc from where I synced the origi

  • Can't get videos to sync with the ipod!

    I have a music video that i want to sync with my ipod, and i can already view the MV in itunes, it is already in my library, but when i try to copy manually the video into the ipod, it does not sync the video! only the song.... I have also tried sett

  • Paymnet without clearing

    Hello Experts, Can we do payment without clearing concept in FICA. Generally we are directly clearing open item as we we run payment. Regards Amit

  • Problem with asyn bpel process assign activity

    hi i m creating asyn bpel process,in my assign activity,i want to copy operation.But it seems that when i expand my input variable it doesnt expand.so i m not able to copy.what would be the reason.anybody suggest me thanks