Stuck on Count Sub Query [ SOLVED ]

A Purchase Order can be receipted in Oracle.
I am using 4 tables here:
po_headers_all - Stores Purchase Order Details
po_lines_all - Stores Purchase Order Line Details
rcv_shipment_lines - Stores Receipt Line Details
rcv_shipment_headers - Stores Receipt Header Details
This simple SQL shows that a PO with 3 lines has been receipted:
SELECT pha.segment1
     , rsh.receipt_num
     , rsh.shipment_header_id
     , rsl.shipment_line_id
  FROM po.po_headers_all pha
     , po.po_lines_all pla
     , po.rcv_shipment_lines rsl
     , po.rcv_shipment_headers rsh
WHERE pha.po_header_id = pla.po_header_id
   AND rsl.shipment_header_id = rsh.shipment_header_id
   AND pla.po_line_id = rsl.po_line_id
   AND pha.segment1 = 1442060;
SEGMENT1             RECEIPT_NUM                    SHIPMENT_HEADER_ID SHIPMENT_LINE_ID
1442060              526312                                     583092          1285161
1442060              526312                                     583092          1285162
1442060              526312                                     583092          1285163Because the PO has 3 lines, and each line has been receipted, there is a corresponsing receipt line in the 'rcv_shipment_lines' table.
I am trying to work out a way to list a PO number, and do a count of how many times that PO has been receipted.
In the above example, the PO has 3 lines, but it has only been receipted once, because all 3 receipt lines share the same Receipt Number.
I have tried this:
SELECT pha.segment1
     , (SELECT (COUNT(*))
          FROM po.rcv_shipment_lines rsl
             , po.rcv_shipment_headers rsh
         WHERE pha.po_header_id = pla.po_header_id
           AND rsl.shipment_header_id = rsh.shipment_header_id
           AND pla.po_line_id = rsl.po_line_id) ct
  FROM po.po_headers_all pha
     , po.po_lines_all pla
WHERE pha.po_header_id = pla.po_header_id
   AND pha.segment1 = 1442060;
SEGMENT1                     CT
1442060                       1
1442060                       1
1442060                       1But clearly that fails because it is counting the fact that each PO line has been receipted and has a corresponding line in the 'rcv_shipment_lines' table.
I can't just join the 'po_headers_all' table to the 'rcv_shipment_lines' table, but have to join via the 'rcv_shipment_lines' table, - the only join is:
'rcv_shipment_lines' joins 'rcv_shipment_lines' via 'shipment_header_id'
And then join the 'rcv_shipment_lines' table to the 'po_lines_all' table, and from there to the 'po_headers_all' table.
I am sorry if I am making a hash of explaining what I am trying to do.
I can supply the table definitions if required, but I haven't done so to start with because it'll make this post even longer.
Thank you

Thanks Dave. This is the result:
SQL> SELECT pha.segment1
  2       , (SELECT COUNT(DISTINCT receipt_num)
  3            FROM po.rcv_shipment_lines rsl
  4               , po.rcv_shipment_headers rsh
  5           WHERE pha.po_header_id = pla.po_header_id
  6             AND rsl.shipment_header_id = rsh.shipment_header_id
  7             AND pla.po_line_id = rsl.po_line_id) ct
  8    FROM po.po_headers_all pha
  9       , po.po_lines_all pla
10   WHERE pha.po_header_id = pla.po_header_id
11     AND pha.segment1 = 1442060;
SEGMENT1                     CT
1442060                       1
1442060                       1
1442060                       1I though then I could do a join via the PO_HEADER_ID instead of going via the po_line_id, and... it works! THANK YOU very much for your help. This forum is such a big help.
This works, in case you are interested:
SELECT pha.segment1
     , (SELECT COUNT(DISTINCT receipt_num)
          FROM po.rcv_shipment_lines rsl
             , po.rcv_shipment_headers rsh
         WHERE rsl.shipment_header_id = rsh.shipment_header_id
           AND pha.po_header_id = rsl.po_header_id) eek
  FROM po.po_headers_all pha
WHERE pha.segment1 = 1442060;Removed 'pha.po_header_id = pha.po_header_id'!

Similar Messages

  • Sub-query got stuck  !!!

    Data
    fcst_retail_value (current Table)
    fcst_entity_id period_id fcst LYfcst
    100     2000     30     null
    100     2002     40     null
    100     2003     70     null
    100 2001 50 null
    200     3000     140 null
    200     3001 400 null
    300     8000     160 null
    300     9000     260 null
    300     4000     270 null
    400     5000     440     null
    400     6000     960     null
    400 7000     900 null
    retail_fcst_map
    fcst_entity_id retail_entity_id
    100               101
    100               102
    100               103
    200               201
    200               202
    300               301
    300               302
    400               401
    400               402
    retail_bucket
    retail_entity_id retail_type_cd retail Period_id
    101          forecasted     30          2000
    102          forecasted 40          2002
    101     forecasted     50          2001
    102 forecasted 70          2003
    202 forecasted     140          3000
    201 forecasted     150          3001
    204 forecasted     250          3001
    301 forecasted     160          8000
    303 forecasted     260          9000
    302 forecasted     270 4000
    401 forecasted     330 6000
    402 forecasted     440 5000
    403 forecasted 500 7000
    404 forecasted 400 7000
    405 forecasted     630 6000
    cal_period
    period_id year cal_id
    2001     2004 45
    2000     2006 45
    2002     2005 45
    2003     2003 45
    3000 2006 44
    3001 2005 44
    3002 2004 44
    8000 2006 43
    9000 2005 43
    4000 2004 43
    5000 2006 42
    6000 2005 42
    7000 2004 42
    OUTPUT NEEDED
    updating fcst_retail_value.lyrdmd with last years data not changing any other data within the table
    fcst_retail_value (2006 DATA + LYDMD populated)
    fcst_entity_id period_id fcst LYfcst
    100          2000          30     40
    100          2002          40     50
    100          2003          70     null
    100 2001 50 70
    200          3000          140 400
    200          3001 400 null
    300          8000          160 260
    300          9000          260 270
    300          4000          270 null
    400          5000          440     960
    400          6000          960     900
    400          7000          900 null
    Tried this but I think i need to write a sub query to go further:
    select sum(db_self.retail_value) as db,
    cp.year, db_self.period_id as dbp,
    cp.period_id as cpp,
    fdv_parent.period_id as fdvp,
    fdv_parent.fcst_entity_id as feid,
    cp.cal_period_id as ccpid,
    cp.cal_id as calid
    cp_ly.year
    from retail_fcst_map dfm, retail_bucket db_self, fcst_retail_value fdv_parent, cal_period cp,cal_period cp_ly
    WHERE dfm.fcst_entity_id = 100
    AND dfm.retail_entity_id = db_self.retail_entity_id
    and db_self.period_id = fdv_parent.period_id
    and dfm.fcst_entity_id = fdv_parent.fcst_entity_id
    and fdv_parent.period_id = cp.period_id
    AND cp_ly.year = cp.year - 1
    Group By db_self.period_id, cp.year, db_self.period_id, cp.period_id, fdv_parent.period_id, fdv_parent.fcst_entity_id, cp.cal_period_id, cp.cal_id;
    Thanks
    mohan

    OUTPUT NEEDED
    I need to update fcst_retail_value.lyfcst with last years data not changing any other data within the table
    fcst_retail_value (2006 DATA + LYDMD populated)
    fcst_entity_id period_id fcst LYfcst
    100 2000 30 40
    100 2002 40 50
    100 2003 70 null
    100 2001 50 70
    200 3000 140 400
    200 3001 400 null
    300 8000 160 260
    300 9000 260 270
    300 4000 270 null
    400 5000 440 960
    400 6000 960 900
    400 7000 900 null

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

  • Error in Sub-Query

    Dear All,
    Based on below image show that the error message, As i know is aggregation problem  in sub query, May i know how to solve it ? thank you.  

    Please have enough Netiquette to post DDL and not pictures. 
    Think about how absurd  "MIN(AVG(AGE)))" on two levels. No, really, you can see that this is absurd if you have any concept of sets. 
    No competent programmer would put age in a column. It is a dynamic value! The constant is birith_date.   Age is computed in the presentation  layers. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Possibility of launch of  a sub query in a query

    Hi developers,
    I have an urgent problem! I have created a query to calculate with a formula an indicator but if I effectue a drill down for customer I have a correct result while when I drill down for country the rows compact the value and the result change in wrong. Is There the possibility or a functionality who allows the launch of a query with selection on another query.
    Have Someone a solution to this problem ?
    Thanks,
    Domeico
    Message was edited by: Domenico Manti

    Hi Domeico,
    I'm not sure I understand your problem correctly, but instead of launching a sub query in a query I would recommend to check, whether a variable with replacement path (reference to characteristic (constant 1)) might solve your problem.
    http://help.sap.com/saphelp_nw04/helpdata/en/03/6ba03cc24efd1de10000000a114084/frameset.htm
    and
    http://help.sap.com/saphelp_nw04/helpdata/en/ca/5f9ac61a205a459d0e7ef313d10321/frameset.htm
    Heike

  • 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

  • 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

  • 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

  • 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

  • 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

  • Scoping violation in sub-query

    I created a sql in Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 to query Oracle Purchasing tables. The user wants to know an estimate of the number of business days it takes to approve a release once it is created. I created a subquery as follows:
    Select Papf.Full_Name As Approver
    , Pah.Action_Date As Approved_Date
    , Por.Creation_Date
    , Trunc(Pah.Action_Date) - Trunc(Por.Creation_Date) As Days
    , (Select Count(*)
    From (Select Level, (Pah.Action_Date+1)-Level My_Date From Dual
    Connect By Level < Trunc(Pah.Action_Date+1) - Trunc(por.creation_Date)
    ) Where To_Char(My_Date, 'DY') In ('MON', 'TUE', 'WED', 'THU', 'FRI')) As Days2Approve
    FROM Apps.Po_Headers_All Poh
    , Apps.Po_Releases_All Por
    , Apps.Po_Lines_All Pol
    , Apps.Po_Action_History Pah
    …etc.
    When I run the query I get the following error message:
    ORA-00904: "POR"."CREATION_DATE": invalid identifier
    00904. 00000 - "%s: invalid identifier"
    *Cause:   
    *Action:
    Error at Line: 193 Column: 54
    I know the sub-query conceptually sound because if I run the sql below with dummy dates I get 17 which is correct.
    Select Count(*)
    From (SELECT level, (to_date('24-JAN-2013')+1)-level my_date From Dual
    Connect By Level < Trunc(To_Date('24-JAN-2013')+1) - Trunc(To_Date('01-JAN-2013'))
    ) Where To_Char(My_Date, 'DY') In ('MON', 'TUE', 'WED', 'THU', 'FRI')
    How do I pass Pah.Action_Date & por.creation_Date to the sub-query without getting what appears to be scoping violation?

    Hi,
    You can avoid the problem by not using a nested sub-query:
        SELECT  COUNT (*)
        FROM    dual
        CONNECT BY   LEVEL  < TRUNC (pah.action_date + 1)
                   - TRUNC (por.creation_date)
        WHERE   TO_CHAR ( pah.action_date + 1 - LEVEL
                          , 'DY'
                  ) NOT IN ('SAT', 'SUN')
    ) AS days2approve 
    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.
    Explain, using specific examples, how you get those results from that data.
    See the forum FAQ {message:id=9360002}

  • 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

Maybe you are looking for

  • Creation of a database engine for mobile devices using j2me

    am trying to develop a database engine for mobile devices.. it is to develop a miniature version of the DBMS that can be deployed on a mobile phone..I have to develop my own code for performing tasks such a s creating a table, inserting values into i

  • Safari iPhone can't play QT movies from certain web pages

    I'm trying to reach QT movies from certain websites and I can't seem to get the streaming video to play in Safari on my iPhone. When I click on the link, it opens a new page. I briefly get a Quicktime logo, then I get a "cannot play" icon (triangle w

  • I get error message in downloading IOS 7.03

    When I download IOS 7.03 on my Pad 2, it always crashes with an error "download failed."   Has anyone faced similar issue?  What is the solution?  Thanks for help.

  • Serious antenna problem!

    With the external antenna a lot of people are having signal issues. If you hold the phone in a way that, your hand covers or touches all three sections of the band, the signal just falls almost instantly. It's terrible and probably the reason for the

  • Auxillary Timecode EDL's?

    I seem to be posting a lot of strange/random questions these days... Is there any way to make an EDL with an Auxillary timecode rather than source timecode? We've got some downconverted DVCam tapes that are being used as our master audio. We may need