Help with itab in a  Query.

Hi;
I need a query that needs the data of the "A004 table pool", but the query doesn't accept this kind of table nor ITAB tables because they are not defined in the BAP dictionary.
How can a mix ITABS or TABLE POOL in a SELECT Statement...?
Thanks on advance.
David Fúnez
Tegucigalpa, Honduras
Corp. Mandofer

Hi;
Thanks for your response.
Ok let me explain what i did...
1) as Atish said... i created a transparent table with the structure of A004 table...
2) i'm trying this to pass data to tne new table but it launches error
A)
LOOP AT a004.
  t_a004-kappl = a004-kappl.
  t_a004-kschl = a004-kschl.
  t_a004-vkorg = a004-vkorg.
  t_a004-vtweg = a004-vtweg.
  t_a004-matnr = a004-matnr.
  t_a004-datbi = a004-datbi.
  t_a004-datab = a004-datab.
  t_a004-knumh = a004-knumh.
  APPEND yestructura.
ENDLOOP.
error message:      "t_a004" is not an internal table - the "OCCURS n" specification is missing.
B)
SELECT * FROM a004 INTO t_a004.
ENDSELECT.
but just pass 1 record.
i need to pass the data to use t_a004 a table created in SE11 with the select statement.
Thaks on advance.
David Fúnez
Tegucigalpa, Honduras
Corp. Mandofer

Similar Messages

  • Help with Converting an Access query

    Hello:
    First time poster and would appreciate some help in converting this Access query into T-SQL so I can use in a Stored Procedure. I don't need help in resolving the syntax for the variables as parameter in the second query, but stuck in writing the first query
    in T-SQL . I assume I need some type of nested query with a left join to another query in T-SQL. 
    How do I convert this from Access into MS-SQL
    SELECT TBL_MONTH.L_Month, TBL_MONTH.L_MonthName
    FROM TBL_MONTH LEFT JOIN qry_MonthCheck ON TBL_MONTH.L_Month = qry_MonthCheck.L_Month
    WHERE (((qry_MonthCheck.L_Month) Is Null));
    qryMonthCheck in Access is defined as
    SELECT TBL_MONTH.L_Month, TBL_SIGNOFF.SO_YEAR, TBL_SIGNOFF.SO_USER, TBL_SIGNOFF.SO_LOCATION
    FROM TBL_MONTH RIGHT JOIN TBL_SIGNOFF ON TBL_MONTH.L_Month = TBL_SIGNOFF.SO_MONTH
    WHERE (((TBL_SIGNOFF.SO_YEAR)=[forms]![frm_signoff]![cboyear]) AND ((TBL_SIGNOFF.SO_LOCATION)=[Tempvars]![tmpVarUserLOC]));

    It is very much up to personal taste. For tables I use no prefix at all. Or suffix. I prefer plural: categories, products, etc. For junction tables, I drop the plural in the first entity, for instance productcategories. As for the case, many people prefer
    initial uppercase, while I go for lowercase only. But initial uppercase has its points, particularly in documentation. I am a staunch advocate of using case-sensitive collation for metadata. I don't see any point in mixing productcategories, Productcategories,
    ProductCategories etc. That can only cause confusion.
    As for either entities, I don't use views much, and I don't have any prefix for these either. In fact, several views I've been involved used to be tables once upon a time.
    If you want to add a marker to the object name, I recommend using a suffix. It is much easier to find objects in the version control system and other browser, when not everything is cluttered on the same letter. For instance, I typically add _sp at the end
    of stored procedure names.
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Help with count and sum query

    Hi I am using oracle 10g. Trying to aggregate duplicate count records. I have so far:
    SELECT 'ST' LEDGER,
    CASE
    WHEN c.Category = 'E' THEN 'Headcount Exempt'
    ELSE 'Headcount Non-Exempt'
    END
    ACCOUNTS,
    CASE WHEN a.COMPANY = 'ZEE' THEN 'OH' ELSE 'NA' END MARKET,
    'MARCH_12' AS PERIOD,
    COUNT (a.empl_id) head_count
    FROM essbase.employee_pubinfo a
    LEFT OUTER JOIN MMS_DIST_COPY b
    ON a.cost_ctr = TRIM (b.bu)
    INNER JOIN MMS_GL_PAY_GROUPS c
    ON a.pay_group = c.group_code
    WHERE a.employee_status IN ('A', 'L', 'P', 'S')
    AND FISCAL_YEAR = '2012'
    AND FISCAL_MONTH = 'MARCH'
    GROUP BY a.company,
    b.district,
    a.cost_ctr,
    c.category,
    a.fiscal_month,
    a.fiscal_year;
    which gives me same rows with different head_counts. I am trying to combine the same rows as a total (one record). Do I use a subquery?

    Hi,
    Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved.
    Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    user610131 wrote:
    ... which gives me same rows with different head_counts.If they have different head_counts, then the rows are not the same.
    I am trying to combine the same rows as a total (one record). Do I use a subquery?Maybe. It's more likely that you need a different GROUP BY clause, since the GROUP BY clause determines how many rows of output there will be. I'll be able to say more after you post the sample data, results, and explanation.
    You may want both a sub-query and a different GROUP BY clause. For example:
    WITH    got_group_by_columns     AS
         SELECT  a.empl_id
         ,     CASE
                        WHEN  c.category = 'E'
                  THEN  'Headcount Exempt'
                        ELSE  'Headcount Non-Exempt'
                END          AS accounts
         ,       CASE
                        WHEN a.company = 'ZEE'
                        THEN 'OH'
                        ELSE 'NA'
                END          AS market
         FROM              essbase.employee_pubinfo a
         LEFT OUTER JOIN  mms_dist_copy             b  ON   a.cost_ctr     = TRIM (b.bu)
         INNER JOIN       mms_gl_pay_groups        c  ON   a.pay_group      = c.group_code
         WHERE     a.employee_status     IN ('A', 'L', 'P', 'S')
         AND        fiscal_year           = '2012'
         AND        fiscal_month          = 'MARCH'
    SELECT    'ST'               AS ledger
    ,       accounts
    ,       market
    ,       'MARCH_12'          AS period
    ,       COUNT (empl_id)       AS head_count
    FROM       got_group_by_columns
    GROUP BY  accounts
    ,            market
    ;But that's just a wild guess.
    You said you wanted "Help with count and sum". I see the COUNT, but what do you want with SUM? No doubt this will be clearer after you post the sample data and results.
    Edited by: Frank Kulash on Apr 4, 2012 5:31 PM

  • Help with doing SELECT sub query within the SET of an UPDATE statement

    After doing some research, it appears as if it's possible to use a SELECT subquery in the SET of an UPDATE statement.  i did find some examples and here is my code, however when I click the "check" button it's saying the field (my entire select subquery) is unknown and neither in one of the specified tables or defined by a "DATA".  Do I have a syntax issue or is there another reason why it's not taking this as a valid statement?  Thanks for the help!
    LOOP AT IT_DATA
    UPDATE /BIC/AZDP_O0140
       SET /BIC/ZCOUNTER = (SELECT COUNT( DISTINCT MATERIAL )
                            FROM /BIC/AZDP_O0140
                            WHERE MATERIAL EQ IT_DATA-MATERIAL
                            GROUP BY MATERIAL).
    ENDLOOP.

    my Update does indeed have a WHERE clause but because of the issue i'm having, all my criteria in my WHERE is black text in the ABAP editor.  The editor doesn't even recognize the keywords "WHERE" or "EQ".  Below is my entire statement which contains all WHERE criteria in both the Update and the Subquery, i've just removed it for testing to help simplify the query and eliminate as many other factors as posisble that may be causing problems:
    LOOP AT IT_DATA.
       UPDATE /BIC/AZDP_O0140
       SET /BIC/ZCOUNTER = (SELECT COUNT( DISTINCT MATERIAL ) FROM /BIC/AZDP_O0140
       WHERE WHSE_NUM EQ IT_DATA-WAREHOUSE
        AND  PLANT EQ IT_DATA-PLANT
        AND  /BIC/ZTRAN_NO EQ IT_DATA-TRANS_NUM
        AND  DELIV_NUMB EQ IT_DATA-DELIVERY
        AND  MATERIAL EQ IT_DATA-MATERIAL
        GROUP BY MATERIAL)
       WHERE WHSE_NUM EQ IT_DATA-WAREHOUSE
        AND  PLANT EQ IT_DATA-PLANT
        AND  /BIC/ZTRAN_NO EQ IT_DATA-TRANS_NUM
        AND  DELIV_NUMB EQ IT_DATA-DELIVERY
        AND  MATERIAL EQ IT_DATA-MATERIAL.
    ENDLOOP.
    i should also mention the sources i found were not within the SAP Library but instead on other third-party ABAP websites.  so because i was having issues i wanted to post here to see if anyone else has come up with a working solution.  but if this cannot be done i can likely come up with a solution for my needs using multiple internal tables, this would just have been much easier since i can get a query like this to do what i want in SQL Server.  Thought i could utilize this in ABAP as well.

  • Need Help with Creating the SQl query

    Hi,
    SQL query gurus...
    INFORMATION:
    I have two table, CURRENT and PREVIOUS.(Table Defs below).
    CURRENT:
    Column1 - CURR_PARENT
    Column2 - CURR_CHILD
    Column3 - CURR_CHILD_ATTRIBUTE 1
    Column4 - CURR_CHILD_ATTRIBUTE 2
    Column5 - CURR_CHILD_ATTRIBUTE 3
    PREVIOUS:
    Column1 - PREV_PARENT
    Column2 - PREV_CHILD
    Column3 - PREV_CHILD_ATTRIBUTE 1
    Column4 - PREV_CHILD_ATTRIBUTE 2
    Column5 - PREV_CHILD_ATTRIBUTE 3
    PROBLEM STATEMENT
    Here the columns 3 to 5 are the attributes of the Child. Lets assume that I have two loads, One Today which goes to the CURRENT table and one yesterday which goes to the PREVIOUS table. Between these two loads there is a CHANGE in the value for Columns either 3/4/5 or all of them(doesnt matter if one or all).
    I want to determine what properties for the child have changed with the help of a MOST efficient SQL query.(PARENT+CHILD is unique key). The Database is ofcourse ORACLE.
    Please help.
    Regards,
    Parag

    Hi,
    The last message was not posted by the same user_name that started the thread.
    Please don't do that: it's confusing.
    Earlier replies give you the information you want, with one row of output (maximum) per row in current_tbl. There may be 1, 2 or 3 changes on a row.
    You just have to unpivot that data to get one row for every change, like this:
    WITH     single_row  AS
         SELECT     c.curr_parent
         ,     c.curr_child
         ,     c.curr_child_attribute1
         ,     c.curr_child_attribute2
         ,     c.curr_child_attribute3
         ,     DECODE (c.curr_child_attribute1, p.prev_child_attribute1, 0, 1) AS diff1
         ,     DECODE (c.curr_child_attribute2, p.prev_child_attribute2, 0, 2) AS diff2
         ,     DECODE (c.curr_child_attribute3, p.prev_child_attribute3, 0, 3) AS diff3
         FROM     current_tbl    c
         JOIN     previous_tbl   p     ON  c.curr_parent     = p.prev_parent
                                AND c.curr_child     = p.prev_child
         WHERE     c.curr_child_attribute1     != p.prev_child_attribute1
         OR     c.curr_child_attribute2     != p.prev_child_attribute2
         OR     c.curr_child_attribute3     != p.prev_child_attribute3
    ,     cntr     AS
         SELECT     LEVEL     AS n
         FROM     dual
         CONNECT BY     LEVEL <= 3
    SELECT     s.curr_parent     AS parent
    ,     s.curr_child     AS child
    ,     CASE     c.n
              WHEN  1  THEN  s.curr_child_attribute1
              WHEN  2  THEN  s.curr_child_attribute2
              WHEN  3  THEN  s.curr_child_attribute3
         END          AS attribute
    ,     c.n          AS attribute_value
    FROM     single_row     s
    JOIN     cntr          c     ON     c.n IN ( s.diff1
                                    , s.diff2
                                    , s.diff3
    ORDER BY  attribute_value
    ,            parent
    ,            child
    ;

  • Help with a "save as" query or an alternative suggestion

    Hi all
    Hope someone can spread some light on this for me, im rather new to using adobe pro - and never ventured into java scripts as yet..
    I have created a pdf document with various text boxes within the document. The document will be pushed out to external users who will only have access to adobe reader.
    My query is this:
    I've created a save button, but can the file name automatically be set to include the data in one of the text fields. I still want the user to chose where to save the document but want the file name to be fixed to the data in the relevant text box.
    If it can be done is it a relatively straight forward procedure.
    If this is not possible, then as an alternative is it possible ible to create maybe a Warning or pop up box after clicking on the "save as" button to prompt the user to save with a different file name to avoid saving over previous versions etc.
    Again if this is this possible, is it difficult to achieve?
    Many thanks in advance for any help!
    Cheers
    Adam

    This tutorial contains a lot of information about saving a file in Acrobat
    using JavaScript:
    http://acrobatusers.com/tutorials/how-save-pdf-acrobat-javascript
    The bottom line is that in order to do it you must have a script installed
    on the local machine.
    The alert is possible, but at the moment it is displayed the user can no
    longer cancel the save command, so you can't really tell them to cancel it
    at that time...

  • Need help with division within a query

    Hello all~
    I am trying to divide these two columns to get a % of case numbers involving an accident. Im pretty sure you need to use decode to avoid the divide by 0 error but not sure how to implement this within my query. When i run this query below, it gives me the result of "1", which is not correct. Can someone help me please?
    Oracle Version 10g
    ACCIDENT is a datatype VARCHAR
    CASE_NUMBER is a datatype VARCHAR
    select to_char(count(ACCIDENT),'999,999,999') as "ACCIDENT",
    to_char(COUNT(CASE_NUMBER),'999,999,999')as "CASE NUMBER",
    round(ratio_to_report(count(accident))
    OVER()*100,2)as "%"
    from      "PURSUIT"
    WHERE ACCIDENT = 'Y'
    AND
    (:P1_BEG_DATE IS NULL AND :P1_END_DATE IS NULL
    OR
    pursuit_date BETWEEN to_date(:p1_beg_date,'MM/DD/YYYY') and to_date
    (:p1_end_date,'MM/DD/YYYY'))
    AND(:P1_TROOP=pursuit.officer_troop OR :p1_troop IS NULL) 
    AND(:P1_RADIO=pursuit.officer_radio OR :p1_radio IS NULL)
    group by case_numberThanks
    Deanna

    Are you sure that the ANDs and ORs in your WHERE clause will take precedence properly?
    Also, if you always select only cases where there has been an accident, what percentage would you like to display? Surely in this case the percentage of cases involving in accident in cases where there was an accident.. is 100%?
    as a simpler example
    SELECT
      accident,
      ROUND(RATIO_TO_REPORT(count(*)) OVER() * 100)
    FROM
      pursuit
    GROUP BY
      accidentHere's a trick to neaten up those IS NULLs:
    SELECT
      accident,
      ROUND(RATIO_TO_REPORT(count(*)) OVER() * 100)
    FROM
      pursuit
    WHERE
      pursuit_date >= COALESCE(:p1_beg_date, pursuit_date) AND
      pursuit_date <= COALESCE(:p1_end_date, pursuit_date) AND
      officer_troop LIKE :p1_troop AND
      offcier_radio LIKE :p1_radio
    GROUP BY
      accidentTo wildcard a date, simply pass NULL in; the coalesce will replace the null with the pursuit_date from the record (thus the >= and <= becomes true)
    To wildcard the troop or the radio, simply pass a '%' symbol as the value of the parameter. If the front end code is already set up to pass nulls, use the COALESCE trick above

  • Help with aggregate function max query

    I have a large database which stores daily oil life, odo readings from thousands of vehicles being tested but only once a month.
    I am trying to grab data from one month where only the EOL_READ = 0 and put all of those values into the previous month's query where EOL_READ = anything.
    Here is the original query which grabs everything
    (select distinct vdh.STID, vdh.CASE_SAK,
    max(to_number(decode(COMMAND_ID,'EOL_READ',COMMAND_RESULT,-100000))) EOL_READ,
    max(to_number(decode(COMMAND_ID,'ODO_READ',COMMAND_RESULT,-100000))) ODO_READ,
    max(to_number(decode(COMMAND_ID,'OIL_LIFE_PREDICTION',COMMAND_RESULT,-100000))) OIL_LIFE_PREDICTION
    from veh_diag_history vdh, c2pt_data_history cdh
    where vdh.veh_diag_history_sak = cdh.veh_diag_history_sak
    and cdh.COMMAND_ID in ('EOL_READ','ODO_READ','OIL_LIFE_PREDICTION')
    and vdh.LOGICAL_TRIGGER_SAK = 3
    and cdh.CREATED_TIMESTAMP =vdh.CREATED_TIMESTAMP
    and cdh.CREATED_TIMESTAMP >= to_date('03/01/2007 12:00:00 AM','mm/dd/yyyy HH:MI:SS AM')
    and cdh.CREATED_TIMESTAMP < to_date('04/01/2007 12:00:00 AM','mm/dd/yyyy HH:MI:SS AM')
    group by vdh.STID, vdh.case_sak
    having count(distinct command_id) = 3
    order by OIL_LIFE_PREDICTION)
    which gives 5 columns:
    STID, CASE_SAK, EOL_READ, ODO_READ, and OIL_LIFE_PREDICTION
    and gives me about 80000 rows returned for the above query
    I only want one reading per month, but sometimes I get two.
    STID is the unique identifier for a vehicle.
    I tried this query:
    I tried this query which nests one request within the other and SQL times out every time:
    select distinct vdh.STID, vdh.CASE_SAK,
    max(to_number(decode(COMMAND_ID,'EOL_READ',COMMAND_RESULT,-100000))) EOL_READ,
    max(to_number(decode(COMMAND_ID,'ODO_READ',COMMAND_RESULT,-100000))) ODO_READ,
    max(to_number(decode(COMMAND_ID,'OIL_LIFE_PREDICTION',COMMAND_RESULT,-100000))) OIL_LIFE_PREDICTION
    from veh_diag_history vdh, c2pt_data_history cdh
    where vdh.veh_diag_history_sak = cdh.veh_diag_history_sak
    and cdh.COMMAND_ID in ('EOL_READ','ODO_READ','OIL_LIFE_PREDICTION')
    and vdh.LOGICAL_TRIGGER_SAK = 3
    and cdh.CREATED_TIMESTAMP =vdh.CREATED_TIMESTAMP
    and cdh.CREATED_TIMESTAMP >= to_date('02/01/2007 12:00:00 AM','mm/dd/yyyy HH:MI:SS AM')
    and cdh.CREATED_TIMESTAMP < to_date('03/01/2007 12:00:00 AM','mm/dd/yyyy HH:MI:SS AM')
    group by vdh.STID, vdh.case_sak
    having count(distinct command_id) = 3
    and vdh.stid in (select distinct vdh.STID, vdh.CASE_SAK,
    max(to_number(decode(COMMAND_ID,'EOL_READ',COMMAND_RESULT,-100000))) EOL_READ,
    max(to_number(decode(COMMAND_ID,'ODO_READ',COMMAND_RESULT,-100000))) ODO_READ,
    max(to_number(decode(COMMAND_ID,'OIL_LIFE_PREDICTION',COMMAND_RESULT,-100000))) OIL_LIFE_PREDICTION
    from veh_diag_history vdh, c2pt_data_history cdh
    where vdh.veh_diag_history_sak = cdh.veh_diag_history_sak
    and cdh.COMMAND_ID in ('EOL_READ','ODO_READ','OIL_LIFE_PREDICTION')
    and vdh.LOGICAL_TRIGGER_SAK = 3
    and cdh.CREATED_TIMESTAMP =vdh.CREATED_TIMESTAMP
    and cdh.CREATED_TIMESTAMP >= to_date('03/01/2007 12:00:00 AM','mm/dd/yyyy HH:MI:SS AM')
    and cdh.CREATED_TIMESTAMP < to_date('04/01/2007 12:00:00 AM','mm/dd/yyyy HH:MI:SS AM')
    group by vdh.STID, vdh.case_sak
    having count(distinct command_id) = 3
    and (max(to_number(decode(COMMAND_ID,'EOL_READ',COMMAND_RESULT,-100000)))) = 0)
    order by OIL_LIFE_PREDICTION
    so in summary I am trying to select values from the previous month only from those stids where this month's value for EOL_READ = 0
    Any ideas.....please help.

    You can use row_number() within each stid and each month to determine the first read of each month. Then you can use lag() to get the previous month's reading of the current month's reading is zero.
    with all_data as (
    select stid,
           case_sak,
           eol_read,
           timestamp,
           row_number() over (partition by stid, trunc(timestamp,'mm') order by timestamp) AS rn
      from veh_diag_history
    select stid,
           case_sak,
           case
             when eol_read = 0
               then lag(eol_read) over (partition by stid order by timestamp)
             else eol_read
           end as eol_read
      from all_data
    where rn = 1;

  • Help with supply and demand query using monthly buckets

    I'm working on a query bound for Discoverer which pulls the aggregated supply and demand for an item and buckets it into months. So for any given item, I need to show the item, onhand, cost, aggregated supply (planned orders, requisitions, pos), and aggregated demand (planned order demand, jobs) - all bucketed by months.
    The code below works okay to find all of the data for July, but I also need to show August and September. I'm thinking I could use a union but am reluctant because the query already runs kind of slow and I'm not sure if I'm on the right track.
    Database Server
    RDBMS : 10.2.0.3.0
    Oracle Applications : 11.5.9
    -Tracy
    select
          item.inventory_item_id, item.organization_code, item.item, item.description
        , item.make_buy,item.planner_code
        , planned.compile_designator, planned.order_type_text, sum(planned.quantity_rate)planned_total
        , planned.mrp_sugg_due_month
        , sum(job.required_quantity-job.quantity_issued)job_open, job.required_month
        , onhand.total_qoh
        , purchase.item_revision prev, purchase.promised_month, purchase.ship_to_organization_id 
        , sum((purchase.quantity-purchase.quantity_cancelled)-purchase.quantity_received)po_open  
        , req.item_revision rrev, req.destination_organization_id, req.org_id, req.need_by_month
        , sum((req.quantity-req.quantity_cancelled)-req.quantity_delivered)req_open
        , cost.item_cost,cost.cost
    from
    --item--
    (select mtl.inventory_item_id, mtl.segment1 item,mtl.description,decode(mtl.planning_make_buy_code,1,'Make',2,'Buy') make_buy
            ,mtl.organization_id, mtp.organization_code, mtl.planner_code
           ,to_char(add_months(sysdate,+1),'YYYY_MM')month1, to_char(add_months(sysdate,+2),'YYYY_MM')month2
           ,to_char(add_months(sysdate,+3),'YYYY_MM')month3
    from    inv.mtl_system_items_b mtl, inv.mtl_parameters mtp
    where    mtl.organization_id = mtp.organization_id
    )item,
    --planned orders - 3 months --
    (select compile_designator,organization_id,inventory_item_id,order_type_text,nvl(quantity_rate,0)quantity_rate,new_due_date
           ,to_char(trunc(new_due_date,'MM'),'YYYY_MM')mrp_sugg_due_month
    from   apps.mrp_orders_sc_v
    where  order_type_text in ('Planned order','Planned order demand')
    and    to_char(trunc(new_due_date,'MM'),'YYYY_MM') <= to_char(add_months(:Month,+2),'YYYY_MM')
    and    to_char(trunc(new_due_date,'MM'),'YYYY_MM') >=  to_char(:Month,'YYYY_MM')
    )planned,
    --jobs - 3 months--
    (select organization_id,wip_entity_name job, inventory_item_id,concatenated_segments,nvl(required_quantity,0)required_quantity
            ,nvl(quantity_issued,0)quantity_issued, date_required,to_char(trunc(date_required,'MM'),'YYYY_MM') required_month
            ,wip_entity_id,creation_date, wip_job_status
    from    apps.wip_requirement_ops_inq_v
    where   primary_item_id <>inventory_item_id
    and     wip_job_status not in ('Closed','Cancelled','Complete')
    and     to_char(trunc(date_required,'MM'),'YYYY_MM') <= to_char(add_months(:Month,+2),'YYYY_MM')
    and     to_char(trunc(date_required,'MM'),'YYYY_MM') >= to_char(:Month,'YYYY_MM')
    )job,
    --qty onhand--
    (select  inventory_item_id,organization_id,sum(nvl(transaction_quantity,0))total_qoh
    from     inv.mtl_onhand_quantities_detail
    group by inventory_item_id, organization_id
    )onhand,
    -- po - 3 months--
    (select pol.item_id, pol.item_revision, nvl(pll.quantity,0)quantity, nvl(pll.quantity_received,0)quantity_received
          , nvl(pll.quantity_rejected,0),nvl(pll.quantity_cancelled,0)quantity_cancelled,poh.segment1 po_num
           ,pll.promised_date, to_char(trunc(pll.promised_date,'MM'),'YYYY_MM')promised_month
           ,pll.shipment_num,pll.ship_to_organization_id 
    from   po.po_lines_all pol, po.po_headers_all poh, po.po_line_locations_all pll
    where  poh.po_header_id = pol.po_header_id
    and    pol.po_header_id = pll.po_header_id
    and    pol.po_line_id = pll.po_line_id
    and    pol.cancel_flag != 'Y'
    and    pol.item_id is not null
    and    to_char(trunc(pll.promised_date,'MM'),'YYYY_MM')<= to_char(add_months(:Month,+2),'YYYY_MM')
    and    to_char(trunc(pll.promised_date,'MM'),'YYYY_MM')>=  to_char(:Month,'YYYY_MM')
    )purchase,
    --reqs - 3 months--
    (select prh.segment1 req_number,nvl(prl.quantity,0)quantity,nvl(prl.quantity_delivered,0)quantity_delivered
           ,nvl(prl.quantity_cancelled,0)quantity_cancelled
           ,prl.destination_organization_id,prl.org_id,prl.item_id,prl.item_revision,prl.need_by_date
           ,to_char(trunc(prl.need_by_date,'MM'),'YYYY_MM')need_by_month
    from   po.po_requisition_headers_all prh, po.po_requisition_lines_all prl
    where  prh.requisition_header_id = prl.requisition_header_id(+)
    and    nvl(prl.cancel_flag,'N') !='Y'
    and    prh.authorization_status != 'CANCELLED'
    and    to_char(trunc(prl.need_by_date,'MM'),'YYYY_MM') <= to_char(add_months(:Month,+2),'YYYY_MM')
    and    to_char(trunc(prl.need_by_date,'MM'),'YYYY_MM') >=  to_char(:Month,'YYYY_MM')
    )req,
    --cost--
    (select msib.inventory_item_id,msib.organization_id,cqm.material_cost,cic.item_cost
    ,(case when cqm.material_cost=0 then cic.item_cost else cqm.material_cost end) cost, cqm.cost_group_id
    from inv.mtl_system_items_b msib
         ,(select cql.cost_group_id,cql.inventory_item_id,cql.organization_id,cql.layer_quantity,cql.material_cost,mp.organization_code
             from bom.cst_quantity_layers cql, inv.mtl_parameters mp
            where mp.default_cost_group_id = cql.cost_group_id) cqm
        ,bom.cst_item_costs cic
    where msib.inventory_item_id = cqm.inventory_item_id(+)
    and msib.organization_id = cqm.organization_id(+)
    and msib.inventory_item_id = cic.inventory_item_id(+)
    and msib.organization_id = cic.organization_id(+)
    )cost
    where item.inventory_item_id = job.inventory_item_id(+)
    and   item.organization_id = job.organization_id(+)
    and   item.month1 = job.required_month(+)  -- 2009_07 --
    and   item.inventory_item_id = onhand.inventory_item_id(+)
    and   item.organization_id = onhand.organization_id(+)
    and   item.inventory_item_id = purchase.item_id(+)
    and   item.month1 = purchase.promised_month(+)  -- 2009_07 --
    and   item.inventory_item_id = req.item_id(+)
    and   item.month1 = req.need_by_month(+)  -- 2009_07 --
    and   item.inventory_item_id = cost.inventory_item_id(+)
    and   item.organization_id = cost.organization_id(+)
    and   item.inventory_item_id = planned.inventory_item_id(+)
    and   item.organization_id = planned.organization_id(+)
    and   item.month1 = planned.mrp_sugg_due_month(+)  -- 2009_07 --
    and   item.make_buy = 'Buy'
    and   item.item in ('161309040','744L755','150-GFM') --test items --
    group by item.inventory_item_id,item.organization_code,item.item,item.description,item.make_buy,item.planner_code
          ,job.required_month ,onhand.total_qoh , purchase.item_revision,  purchase.promised_month
            ,purchase.ship_to_organization_id  ,cost.item_cost,cost.cost
           ,req.item_revision, req.destination_organization_id,req.org_id,req.need_by_month
           ,planned.compile_designator,planned.order_type_text,planned.mrp_sugg_due_month
    order by item.organization_code,item.item

    Hi,
    Six things:
    (1) Where are the one-to-many relationships between your tables? If a single row in mtl can match two (or more) rows in mrp, and can also match two (or more) rows in wip, then it looks like, when you join both of them them, you'll have a chasm trap, that is, you'll get all the matching rows from mrp paired with all matching rows from wip. Are you sure your existing query is producing the right results?
    Are there one-to-many relationships with the other tables in your original query?
    (2) Are your DATEs always at midnight? If not, avoid using BETWEEN and LAST_DAY for DATE comparisons: otherwise you'll miss everything between 00:00:01 and 23:59:59 on the last day.
    That is, instead of
    and     mrp.new_due_date(+) BETWEEN :Month AND LAST_DAY(ADD_MONTHS(:Month,2))ypou should say
    and       mrp.new_due_date (+)     >= :Month
    and       mrp.new_due_date (+)     <  ADD_MONTHS (:Month, 3)(3) The basic way to pivot the months of mrp_due_date is:
    SELECT    ...
    ,       NVL ( SUM ( CASE
                     WHEN  mrp.new_due_date >= :month
                     AND   mrp.new_due_date < ADD_MONTHS (:month, 1)
                     THEN  mrp.quantity_rate
                    END
               , 0
               )          AS mrp_qty_0
    ,       NVL ( SUM ( CASE
                     WHEN  mrp.new_due_date >= ADD_MONTHS (:month, 1)
                     AND   mrp.new_due_date <  ADD_MONTHS (:month, 2)
                     THEN  mrp.quantity_rate
                    END
               , 0
               )          AS mrp_qty_1When you do this, do not GROUP BY TRUNC (mrp.new_due_date, 'MM').
    The code above does two months: I'm sure you get the idea for how to do more.
    To get dynamic column headings (such as Jun_2009 or "2009-06" instead of the generic mrp_qty_o) requires dynamic SQL. The best way to do dynamic SQL depends on the tool that is producing the query (e.g. SQL*Plus). What are you using? Are you willing to change, if it helps?
    (4) Displaying separate columns from one row as a single column on multiple rows is called unpivoting. How badly do you want to do that? Your query would be simpler and faster if the output had only one row per group (rather than one row for mrp_qty and another row for wip_wty). That one row could have six columns (e.q. June_mrp, June_wip, July_mrp, July_wip, August_mrp and August_wip) instead of three. Depending on your front-end tool, you might even be able to wrap the single row of output so that it always appeared as two rows, each with three columns.
    (5) Sorry I told you to do
    and     mrp.order_type_text(+) in (...)I never use the + outer-join notation any more, so I forgot about the ORA-01719 error. There's no problem having an outer-join condition like that using ANSI notation. (One more reason to switch.)
    (6) As you noticed, this site doesn't like to print the &lt;&gt; inequality operator, even inside tags.
    Use the equivalent != operator instead, when posting on this site.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Continuation-Please help with a complex sql query

    Hi all,
    Thanks a lot for your suggestions and inputs in the last thread of this post.
    With the help of your suggested approach,i went ahead and was able to get some more data in the format as needed..I worked on gradually adding one table after another exactly as the data is required stepwise.But,still I am facing issues with displaying them.
    there are many issues I am not able to do and would appreciate if you please have a look at my latest modified SELECT given below and help me writing it to get the display as needed.
    Below,is the attempted query i tried out using your inputs.But,am stuck and need your help in writing it.
    **Here,there is 1 ->MANY lines for the t_objective_id--->This has many learning_record_ids which i want to group by the unique objective_id.
    Also,prior to that,there is a tplan_id---->which has MANY t_objective_id's
    SELECT DECODE (LAG (firstname, 1, 0) OVER (ORDER BY firstname),
                   firstname, ' ',
                   firstname
                  ) firstname,
           DECODE (LAG (emplid, 1, 0) OVER (ORDER BY emplid),
                   emplid, ' ',
                   emplid
                  ) emplid,
           DECODE (LAG (tplan_name, 1, 0) OVER (ORDER BY tplan_name),
                   tplan_name, ' ',
                   tplan_name
                  ) tplan_name,
                  tplan_id,
                  DECODE (LAG (activities, 1, 0) OVER (ORDER BY activities),
                   activities, ' ',
                   activities
                  ) activities,
                  activities,
                  --activities,
           DECODE (LAG (t_objective_id, 1, 0) OVER (ORDER BY t_objective_id),
                   t_objective_id, ' ',
                   t_objective_id
                  ) t_objective_id,           
                   completed_activities,required_credits,
          DECODE (LAG (learning_record_id, 1, 0) OVER (ORDER BY learning_record_id),
                   learning_record_id, ' ',
                   learning_record_id
                  ) learning_record_id,           
                   catalog_item_name,catalog_item_type           
      FROM (SELECT test_cp.firstname, test_op.emplid, tp.tplan_name,tp.tplan_id,FN_TP_GET_CMPLTD_ACT_CNT(tp.tplan_id,test_lp.lp_person_id,'1862') activities,
                   test_tpo.t_objective_id,
                   (  fn_tp_obj_comp_req_act_cdt (test_lp.lp_person_id,
                                                  tp.tplan_id,
                                                  test_tpo.t_objective_id,
                                                  tp.is_credit_based
                    + fn_tp_obj_comp_opt_act_cdt (test_lp.lp_person_id,
                                                  tp.tplan_id,
                                                  test_tpo.t_objective_id,
                                                  tp.is_credit_based
                   ) completed_activities,test_tpo.required_credits,lr.learning_record_id,lr.catalog_item_name,lr.catalog_item_type
              FROM test_learning_plan test_lp,
                   test_training_plan tp,
                   test_person test_cp,
                   test_org_person test_op,test_tp_learning_activity test_tplplr,
                   test_tp_objective test_tpo,test_learning_record lr,test_train_obj_activity tpobjact
             WHERE test_lp.lp_person_id = '1862188559'
               AND test_cp.person_id = test_lp.lp_person_id
               AND tp.tplan_id = 'tplan200811200632352287621599'
               AND test_tpo.t_objective_id = tpobjact.t_objective_id
               AND test_lp.LP_CATALOG_HIST_ID = tp.tplan_id
               AND test_tplplr.tp_lp_lr_id =test_lp.learning_plan_id
               AND test_tplplr.activity_lp_lr_id = lr.learning_record_id
               AND lr.LR_CATALOG_HISTORY_ID = tpobjact.activity_id
               AND test_op.o_person_id = test_cp.person_id
               AND test_tpo.tplan_id = tp.tplan_id)
    If we see the outer SELECT ---then one of the main issues is for EACH t_objective_id----->There are n learning_record_ids.
    But,this select only shows 1 learning_record_id for each objective_id which is wrong.
    Similarly,the data displayed isnot proper.
    Below is the way I am getting the data now from the above SELECT.
    Note:- FIRSTNAME is not correctly displayed.
    FIRSTNAME     EMPLID     TPLAN_NAME     TPLAN_ID     ACTIVITIES     ACTIVITIES_1  
                      001                TP1          tplan1          5          5
    TESTNAME                                              tplan1           5          
    Continuation of the other columns of the same rows--**couldnt paste it properly so.
    T_OBJECTIVE_ID     COMPLETED_ACTIVITIES     REQUIRED_CREDITS     LEARNING_RECORD_ID        CATALOG_ITEM_NAME     CATALOG_ITEM_TYPE
              obj1               1                         5                         lr1                            C1                          Course
                    obj2               4                        4          

    Something like this might solve your problem ->
    satyaki>
    satyaki>select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Prod
    PL/SQL Release 10.2.0.1.0 - Production
    CORE    10.2.0.1.0      Production
    TNS for Linux: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - Production
    Elapsed: 00:00:00.00
    satyaki>
    satyaki>
    satyaki>select * from emp;
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7521 WARD       SALESMAN        7698 22-FEB-81     226.88        500         30
          7654 MARTIN     SALESMAN        7698 28-SEP-81       1815       1400         30
          7788 SCOTT      ANALYST         7566 19-APR-87     598.95                    20
          7839 KING       PRESIDENT            17-NOV-81       7260                    10
          7844 TURNER     SALESMAN        7698 08-SEP-81       2178          0         30
          7876 ADAMS      CLERK           7788 23-MAY-87     159.72                    20
          7900 JAMES      CLERK           7698 03-DEC-81     1379.4                    30
          7902 FORD       ANALYST         7566 03-DEC-81    5270.76                    20
          7934 MILLER     CLERK           7782 23-JAN-82     1887.6                    10
          7566 Smith      Manager         7839 23-JAN-82       1848          0         10
          7698 Glen       Manager         7839 23-JAN-82       1848          0         10
         EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTNO
          7599 BILLY      ANALYST         7566 10-JUN-09       4500                    30
    12 rows selected.
    Elapsed: 00:00:00.00
    satyaki>
    satyaki>
    satyaki>
    satyaki>
    satyaki>select decode(lag(job,1,null) over(order by job),'CLERK','CK',
      2                                                   'SALESMAN', 'SM',
      3                                                   'ANALYST','AL',
      4                                                   'BO') res
      5  from emp;
    RE
    BO
    AL
    AL
    AL
    CK
    CK
    CK
    BO
    BO
    BO
    SM
    RE
    SM
    12 rows selected.
    Elapsed: 00:00:00.01
    satyaki>
    satyaki>
    satyaki>select MAX(decode(lag(job,1,null) over(order by job),'CLERK','CK',
      2                                                   'SALESMAN', 'SM',
      3                                                   'ANALYST','AL',
      4                                                   'BO')) res
      5  from emp;
    select MAX(decode(lag(job,1,null) over(order by job),'CLERK','CK',
    ERROR at line 1:
    ORA-30483: window  functions are not allowed here
    Elapsed: 00:00:00.01
    satyaki>
    satyaki>select MAX(res)
      2  from (
      3          select decode(lag(job,1,null) over(order by job),'CLERK','CK',
      4                                                           'SALESMAN', 'SM',
      5                                                           'ANALYST','AL',
      6                                                           'BO') res
      7          from emp
      8     );
    MA
    SM
    Elapsed: 00:00:00.00
    satyaki>
    satyaki>Regards.
    Satyaki De.

  • Help with a simple XMLTable query

    Newbie Oracle XML developer here and need a little guidance on how to retrieve multiple records in an xmltype table using xmltable.
    My document in the xmltype table looks like this:
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <echoems:ECHOMetrics xmlns:echoems="http://myURL/myFilename.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://myURL/myFilename.xsd
    http://myURL/myFilename.xsd">
    <OrderMetrics>
    <OrderItemMetric>
    <requestor>user1</requestor>
    <product>123</product>
    </OrderItemMetric>
    <OrderItemMetric>
    <requestor>0.0.0.0</requestor>
    <product>ABC</product>
    </OrderItemMetric>
    <OrderItemMetric>
    <requestor>user3</requestor>
    <product>XYZ</product>
    </OrderItemMetric>
    </OrderMetrics>
    </echoems:ECHOMetrics>
    I want to get all the products:
    Product
    123
    ABC
    XYZ
    I know to use XMLTable but am not sure how exactly to write it. If just one record, the following worked fine:
    select extractvalue
    (object_value,
    'echoems:ECHOMetrics/OrderMetrics/OrderItemMetric/product',
    'xmlns:echoems="http://myURL/myFilename.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
    ) object_value
    from echoXML;
    But with multiple records, I'm trying XMLTable but can't get it right. Trying something like this:
    select m.product
    from echoXML3
    xmlTable(
    (object_value,'echoems:ECHOMetrics/OrderMetrics/OrderItemMetric/*','xmlns:echoems="http://myURL/myFilename.xsd')
    passing object_value
    COLUMNS
    product varchar2(85) path 'product') m;
    Thanks in advance for any help on this.

    One more question. Instead of putting the xml doc in the query, how do I reference it from the xmlType table?
    You have:
    select *
    from xmltable
    '//OrderMetrics/OrderItemMetric'
    passing xmltype(
    '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <echoems:ECHOMetrics xmlns:echoems="http://myURL/myFilename.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://myURL/myFilename.xsd">
    <OrderMetrics>
    <OrderItemMetric>
    <requestor>user1</requestor>
    <product>123</product>
    </OrderItemMetric>
    <OrderItemMetric>
    <requestor>0.0.0.0</requestor>
    <product>ABC</product>
    </OrderItemMetric>
    <OrderItemMetric>
    <requestor>user3</requestor>
    <product>XYZ</product>
    </OrderItemMetric>
    </OrderMetrics>
    </echoems:ECHOMetrics>')
    columns
    prod varchar2(20) path 'product',
    requestor varchar(50) path 'requestor'
    However, the xmlDocument is already in an xmlType table called echoXML3 based on the xsd. I'm just trying to query it to get a relational result set. How, in the query above, do I replace the hardcoded xmlDoc with the xmlDoc located in my xmlType table?
    I thought maybe something like this but it's not working:
    select *
    from xmltable
    '//OrderMetrics/OrderItemMetric'
    passing xmltype(select value(e)
    from echoXML3,
    TABLE(xmlsequence(extract(object_value,'echoems:ECHOMetrics/OrderMetrics/OrderItemMetric/*','xmlns:echoems="http://myURL/myFilename.xsd'))) e)
    columns
    prod varchar2(20) path 'product',
    requestor varchar(50) path 'requestor'
    Message was edited by:
    user619814

  • Help with Finding Duplicate records Query

    HI,
    I am trying to write a query that will find duplicate records/cases.
    This query will be used in a report.
    So, here are the requirements:
    I need to find duplicate cases/records based on the following fields:
    DOB, DOCKET, SENT_DATEI was able to do that with the following query. The query below is able to give me all duplicate records based on the Criteria above
    SELECT      DEF.BIRTH_DATE DOB,
               S.DOCKET DOCKET,
               S.SENT_VIO_DATE SENT_DATE, COUNT(*)
    FROM SENTENCES S,
                DEFENDANTS DEF
    WHERE      S.DEF_ID = DEF.DEF_ID
    AND       S.CASE_TYPE_CODE = 10
    GROUP BY  DEF.BIRTH_DATE, S.DOCKET, S.SENT_VIO_DATE
    HAVING COUNT(*) > 1;
    //I AM GOING TO CALL THIS QUERY 'X'Now, the information to be displayed on the report: defendants Name, DOB, District, Docket, Def Num, Sent Date, and PACTS Num if possible.
    The problem that I need help on is how to combine those queries together (what I mean is a sub query). the 'X' query returns multiple values. please have a look at the comments on the query below to see what I'm trying to achieve.
    here is the main query:
    SELECT      INITCAP(DEF.LAST_NAME) || ' ' || INITCAP(DEF.FIRST_NAME) || ' ' || INITCAP(DEF.MIDDLE_NAME) DEFENDANT_NAME,
            DEF.BIRTH_DATE DOB,
            TRIM(DIST.DISTRICT_NAME) DISTRICT_NAME,
            S.DOCKET DOCKET,
            S.DEF_NUM DEF_NUM,
            S.SENT_VIO_DATE SENT_DATE,
            DEF.PACTS_ID PACTS_NUM
    FROM      USSC_CASES.DEFENDANTS DEF,
            USSC_CASES.SENTENCES S,
            LOOKUP.DISTRICTS DIST
    WHERE      DEF.DEF_ID = S.DEF_ID
    AND      S.DIST_ID = DIST.USSC_DISTRICT_ID
    AND     S.CASE_TYPE_CODE = 10
    AND     S.USSC_ID IS NOT NULL
    AND // what i'm trying to do is: DOB, DOCKET, SENT_DATE IN ('X' QUERY), is this possible ??
    ORDER BY DEFENDANT_NAME; thanks in advance.
    I am using Oracle 11g, and sql developer.
    if my approach doesn't work, is there a better approach ?
    Edited by: Rooney on Jul 11, 2012 3:50 PM

    If I got it right, you want to join table USSC_CASES.DEFENDANTS to duplicate rows in USSC_CASES. If so:
    SELECT  INITCAP(DEF.LAST_NAME) || ' ' || INITCAP(DEF.FIRST_NAME) || ' ' || INITCAP(DEF.MIDDLE_NAME) DEFENDANT_NAME,
            DEF.BIRTH_DATE DOB,
            TRIM(DIST.DISTRICT_NAME) DISTRICT_NAME,
            S.DOCKET DOCKET,
            S.DEF_NUM DEF_NUM,
            S.SENT_VIO_DATE SENT_DATE,
            DEF.PACTS_ID PACTS_NUM
      FROM  USSC_CASES.DEFENDANTS DEF,
             SELECT  *
               FROM  (
                      SELECT  S.*,
                              COUNT(*) OVER(PARTITION BY DEF.BIRTH_DATE, S.DOCKET, S.SENT_VIO_DATE) CNT
                        FROM  USSC_CASES.SENTENCES S
               WHERE CNT > 1
            ) S,
            LOOKUP.DISTRICTS DIST
      WHERE DEF.DEF_ID = S.DEF_ID
       AND  S.DIST_ID = DIST.USSC_DISTRICT_ID
       AND  S.CASE_TYPE_CODE = 10
       AND  S.USSC_ID IS NOT NULL
      ORDER BY DEFENDANT_NAME;If you want to exclude duplicates from the query and do not care which row out of duplicate rows to choose:
    SELECT  INITCAP(DEF.LAST_NAME) || ' ' || INITCAP(DEF.FIRST_NAME) || ' ' || INITCAP(DEF.MIDDLE_NAME) DEFENDANT_NAME,
            DEF.BIRTH_DATE DOB,
            TRIM(DIST.DISTRICT_NAME) DISTRICT_NAME,
            S.DOCKET DOCKET,
            S.DEF_NUM DEF_NUM,
            S.SENT_VIO_DATE SENT_DATE,
            DEF.PACTS_ID PACTS_NUM
      FROM  USSC_CASES.DEFENDANTS DEF,
             SELECT  *
               FROM  (
                      SELECT  S.*,
                              ROW_NUMBER() OVER(PARTITION BY DEF.BIRTH_DATE, S.DOCKET, S.SENT_VIO_DATE ORDER BY 1) RN
                        FROM  USSC_CASES.SENTENCES S
               WHERE RN = 1
            ) S,
            LOOKUP.DISTRICTS DIST
      WHERE DEF.DEF_ID = S.DEF_ID
       AND  S.DIST_ID = DIST.USSC_DISTRICT_ID
       AND  S.CASE_TYPE_CODE = 10
       AND  S.USSC_ID IS NOT NULL
      ORDER BY DEFENDANT_NAME;SY.

  • Help with re-writing this query

    Dear experts;
    create table t2
      ID varchar2(1000),
      name varchar2(1000),
       place varchar2(1000)
    create table mappingt2
      grades varchar2(1000)
      individual varchar2(1000)
    insert into t2 values ('James', 'John', 'newyork');
    insert into t2 values ('Linda', 'James', 'London');
    insert into t2 values ('Alex', 'kim', 'Mexico');
    insert into t2 values ('karen', 'Jack', 'Tunis');
    insert into t2 values ('CC', 'Jack', 'Peru');
    insert into t2 values ('Linda', 'James', 'Germany');
    insert into mappingt2 values ('A', 'James');
    insert into mappingt2 values ('C', 'Kim');
    insert into mappingt2 values ('C', 'Linda');
    insert into mappingt2 values ('B', 'CC');I have the following query below
    SELECT (select grades from mappingt2 t
       where t.individual =  pt.ID) as current_grade
          ,(select grades from mappingt2 ty
       where ty.individual =  pt.name) alt_grade
          ,pt.place
      FROM t2 ptI was just wondering whether this query can be better written. All help is appreciated. Thank you

    user13328581 wrote:
    Hi Frank, Tom Kyte claims sub scalar queries is usually betterHe didn't say usually he said if you want the first row faster
    >
    if your goal is to optimize your query for initial response time, you may want to use the former query, with the scalar subquery, because Oracle Database would have to get just the first row from DEPT, run the scalar subquery (select count...) against EMP to get the count, and then return it. The process for returning that first row would be very fast.
    >
    The corollary to this that was not explicitly mentioned in the article that I can see is that this probably comes at the expense of the time taken to return all the rows which can then take longer.

  • Help with poplist record group query

    Hi, I want to populate a poplist based on the following query:
    SELECT value
    FROM table.value
    WHERE code_parent IS NULL
    UNION ALL
    SELECT 'ALL'
    FROM dual
    ORDER
    BY code
    Now I know that you need 2 columns in the record group to populate a poplist, but I cannot seem to modify the query to have 2 columns. I am basically adding the 'ALL' value, which will have a label of 'ALL' and a value of 'ALL'.
    The first select I can easily modify to be an acceptable record group for a dynamic poplist, Its the union that im having problems with. The following select does not work. Help would be appreciated.
    SELECT table.value, table.value
    FROM table.value
    WHERE code_parent IS NULL
    UNION ALL
    SELECT 'ALL', 'ALL'
    FROM dual
    ORDER
    BY table.value

    Based on the error I'd guess that one of your columns are defined as a number and the union columns are both varchar2. Match the datatype with the column it corresponds to:
    UNION
    SELECT 'ALL', 0
    FROM DUAL
    ORDER BY 1
    The order by clause also needs to reference the column number instead of the column name since the union clause does not have a column name.

  • Help with an advance mysql query

    I'm using CF 7 to query a MySQL 5 DB.
    I was wondering if it's possible to add an OR operator in a
    subquery or at the end of a conditional statment. Let's say that in
    my conditional WHERE statement after a few inclusive conditions, I
    wanted to add an "AND & OR" logic.
    maybe by including part of my code I can be a little more
    clear:
    <cfquery name="domysearch" ...>
    SELECT
    a.id as id,
    b.company as company,
    c.add_line1 as add_line1,
    FROM registratn_contacts a, registratn b,
    registratn_addresses c
    WHERE a.owner = #arguments.owner#
    AND b.id = a.master_record
    AND c.id = a.address_id
    AND c.state = 'NY'
    OR c.state = 'CA'
    I would like to know if I can or should accomplish this in my
    query or if I should have this logic outside the query?
    Thanks for any help!!!!
    Carlos

    WHERE .....
    AND (c.state = 'NY' OR c.state = 'CA')
    You can use an OR, but it is probably
    better to use an IN clause, as it is essentially an OR, and
    would be more efficient.
    AND c.state IN ( 'NY', 'CA')
    Phil

Maybe you are looking for

  • Display image in JSP

    Hi, I'm having problems allowing users to upload images within my j2ee application and then displaying them again. Does anybody have any tips? I don't really want to store the image in the db (just the image name), but I can't figure out where to put

  • Oracle Rdb Driver 3.1.0.0 problem

    I am trying to convert an MsAccess application to use an MsAccess front end and an Oracle Rdb back end. I've created the test database under VMS and can successfully link to the Oracle Rdb tables from MSAccess 2000. One of the main reasons for conver

  • Classify condition types

    Dear Friends, I am having four different pricing procedures for Export /Domestic/Scrap and Adjustment (Credit and Debit memo pricing). Do I need to update the Adjustment pricing procedure as well under the Tax on Goods Movements> Condition-Based Exci

  • C Function in ABAP

    Hi, Is there a way to debug a C function in ABAP. How can I view it's source code from the system ? BR, Rotem.

  • I can't see tiff files

    I'm trying to import tiff files into aperture from a epson scanner but I can't even see them. Any answers? thanks