Complex query (choose between 2 fields) W/O Decode

Hi,
I have following fields in a table..
Old_Account_Num
Account_Num
Sometimes 'Account_Num' may have values like ' ' & '999'. In that case I want to get 'Old_Account_Num'
right now I am achieveing this like below
(Select
DECODE (Account_Num,' ', Old_Account_Num,'999', Old_Account_Num,Account_Num) AS AccountNumber
From MobileShipments) SM
Everytime I am using this table, I have to write a query like, make that as inner query around main query. Is there any other way to handle this so that I don't have write this one as inner query. (like using PARTITION BY etc something.. which I am not sure)
Complete Query:
SELECT UAS.Account_Num as MainAccount,UAS.Name, IS.ItemCodeFROMMobileShipments MS, UserAccount UAS, Items IS(Select DECODE (Account_Num,' ', Old_Account_Num,'999', Old_Account_Num,Account_Num) AS AccountNumber,SUM(SAMOUNT) as Amount,SUM(PAmount) as PendingAmountFrom MobileShipments M, UserAccount UAWHERE M.ACTID = UA.ACTIDGROUP BY DECODE (Account_Num,' ', Old_Account_Num,'999', Old_Account_Num,Account_Num)) MSWHERE UAS.Account_Num = MS.AccountNumberAND UAS.ID = IS.ID
I am using Oracle 9
Thanks in advance

SeshuGiri
OK, you're on 9i, so you can't use virtual columns. Let's have a closer look at your query.
SELECT UAS.Account_Num as MainAccount
     ,UAS.Name
     , IS.ItemCode
FROM MobileShipments MS
   , UserAccount UAS
   , Items IS
   ,(Select DECODE (Account_Num,' ', Old_Account_Num,'999', Old_Account_Num,Account_Num) AS AccountNumber
        ,SUM(SAMOUNT) as Amount
        ,SUM(PAmount) as PendingAmount
   From MobileShipments M
       , UserAccount UA
   WHERE M.ACTID = UA.ACTID
   GROUP BY DECODE (Account_Num,' ', Old_Account_Num,'999',Old_Account_Num,Account_Num)
   ) MS
WHERE UAS.Account_Num = MS.AccountNumberAND UAS.ID = IS.IDThe inline view includes a GROUP BY (which you didn't mention before).
Can you label up your statement so we can see which column is in which table? Prefix each column with the relevant tablename (or aliasname).
You include MobileShipments twice, and UserAccounts twice. Are you sure that's necessary? Why not do the whole thing in a single query?
You have the inline view aliased as MS - but so is the first table in the from list (MobileShipments). That won't work.
You may have problems using IS as an alias, as it is also a keyword.
You do the GROUP BY but you aren't selecting any of the columns from it - all that will do is mean that you will waste a lot of effort.
Can you post the query again - maybe with the table definitions (at least, the relevant columns)
Regards Nigel

Similar Messages

  • Creating a dynamic query by choosing the field and getting the report

    Hi,
    Is there a way to create a report by allowing the user to choose a field from the table and design a query based on that field.
    Ex In a table students with fields
    (StudentNo, StudentName,Age,Qualification,Hobbies, PlaceofBirth)
    Is it possible to generate a query
    select * from students where Hobbies=programming;
    where the user can be given the option of selecting the field and the value (Hobbies, programming), the query is generated for that, then the report is designed for that query. How could the query be generated?
    Regards,
    Reshma

    You sure can ;)
    Here's an example.
    You can create a JComboBox and have the different categories of hobbies in there and then use ActionListener on the JcomboBox.
    The code will be something like this
    public void actionPerformed(ActionEvent ae)
      if(ae.getSource()==combo)    //assuming the JComboBox object is combo
        String query=new String("");
        String st = combo.getSelectedItem().toString();
        Connection connection=DriverManager.getConnection("jdbc:odbc:DSN","user","password");
        Statement stmt=connection.createStatement();
        String qry="SELECT * FROM tablename WHERE hobby=";
        String query=qry+st;
        ResultSet rs=stmt.execute(query);     //Then do whatever you want with the ResultSet object
    }

  • JHeadstart query operator between with date field

    Hallo,
    I am using JDeveloper 10.1.1.0.2 and JHeadstart 11 Technical Release 1.
    In my Application Definition Editor I use the Query Operator 'between' on a data-field. In my Application I can see a 'from' and 'to' date field.
    Testcase:
    In my table I have 3 dates: 1-1-2009, 17-1-2009 and 18-1-2009.
    If I use:
    Date from: 1-1-2009 and Date to: 18-1-2009 in my Application I expect to see only 2 rows (1-1-2009 and 17-1-2009). But I can see 3 rows.
    So my question is: what does 'to' mean in the JHeadstart generator? Does it include the date you fill in with the 'to' field?

    I can change the text in GeneratorText_nl.properties, but this does not completely solve my problem.
    I use a DateTimeField in my Application and if I use 'Date to' in my search criteria it seems that the Time of my Date-field is being ignored!
    Testcase:
    'Date to' in searchcriteria = 13-10-2009 *12:10:00* also gives results with the same date but time greater than 12:10:00, for example 13-10-2009 *16:10:00*.

  • How to bind local variables in complex query in PL/SQL

    Hi
    I have long complex query with local varibales; when I run in Dynamic SQL I get an error. Not sure which is the easiest way to bind local variables.
    L_QUERY := q'[select m.segment1 col1,
          '1' col2,
          '13' col3,
          l.operand col4,
          0 col5,
           'Y' col8,
          'N' col9,
          'N' col10,
       decode(h.name,'09_UKOR_*','EOS Credit','10_UKOR_*','TopUp','11_UKOR_*','Main') col18
    from qp_list_headers_v h,
          qp_list_lines_v l,
          mtl_system_items m
    where h.name in ('09_UKOR_*','10_UKOR_*','11_UKOR_*')
    and h.list_header_id = l.list_header_id
    and m.inventory_item_id = l.product_attr_value
    and m.organization_id  = 84
    UNION all
    SELECT qs.PRODUCT_ATTR_VALUE col1,
           hca.account_number col2,
           decode (su.site_use_code,'BILL_TO','21','SHIP_TO','18') col3,
           0 col4,
           qs.operand col5,
           null col6,
           null col7,
           'N' col8,
           'Y' col9,
           'N' col10,     
    --Local variables
          (case when (trunc(nvl(qq.start_date_active,sysdate)) between l_cur_year_from  and l_cur_year_to) and  
                      ( trunc(nvl(qq.end_date_active,l_cur_year_to)) >= trunc(l_cur_year_to) )  then    'TopUp'
                when (trunc(qq.start_date_active) between l_next_year_from  and l_next_year_to) and  
                      ( trunc(nvl(qq.end_date_active,l_next_year_to)) >= l_next_year_to)  then   'Main'              
                when (trunc(qq.start_date_active) between l_last_year_from  and l_last_year_to) and  
                      ( trunc(nvl(qq.end_date_active,l_last_year_to)) >= l_last_year_to )  then  'EOS Return'
           end )col18,
    --Local variables
           (case   when (trunc(qq.start_date_active) between l_next_year_from  and l_next_year_to) and  
                      ( trunc(nvl(qq.end_date_active,l_next_year_to)) >= l_cur_year_to )  then   'N'
              else
                    'Y'  end ) col21
       FROM qp.qp_list_headers_b qlhb,
            qp.qp_list_headers_tl qlht,
            qp.qp_qualifiers qq,
            qp_modifier_summary_v qs,
            hz_cust_site_uses_all su,
            hz_cust_acct_sites_all  sa,
            hz_cust_accounts hca
    WHERE 1=1
          and qlhb.LIST_TYPE_CODE       = 'DLT'
          and nvl(qlhb.active_flag,'Y') = 'Y'
          and qlhb.list_header_id       = qlht.list_header_id
          AND qq.list_header_id         = qlhb.list_header_id
          and qq.list_type_code         = qlhb.LIST_TYPE_CODE
          and qq.QUALIFIER_CONTEXT      = 'CUSTOMER'
          and qs.list_header_id         = qlhb.list_header_id
          and qs.LIST_LINE_TYPE_CODE    = 'DIS'
          and su.site_use_id            = qq.qualifier_attr_value --1064
          AND  su.cust_acct_site_id     = sa.cust_acct_site_id
          AND  sa.cust_account_id       = hca.cust_account_id ]';
    --call Dynamic SQL function
    l_cursor := DBMS_SQL.OPEN_CURSOR;
    DBMS_SQL.PARSE(l_cursor, p_QUERY , DBMS_SQL.NATIVE);
    l_rows := DBMS_SQL.EXECUTE(l_cursor);
    Any help will be much appreciated.
    iI guess I should use DBMS_SQL.BIND_VARIABLE to bind all variables seperately so not to mess with query

    1) What is the error you get?
    2) If you use bind variables inside a query, you should prefix them with colons, so use :l_cur_year_from etc.
    3) Why are you using dbms_sql instead of native dynamic sql and/or ref-cursors?
    Toon

  • Trying to form complex query - need help

    I have a fairly complex query that I need to join the results of to show actual and goal by day. The actuals are an aggregation of records that get put in every day, while the targets are a single entry in range format indicating an active range for which the target applies. I'm working on a query that will put things together by month and I'm running into a snag. Can someone please point out where appropriate naming needs to go to get this to come together?
    This one works:
    (select DATE_INDEX, SUM(LDS) as TTLLDS, SUM(TONS) as TTLTONS from
        (select DATE_INDEX, VEH_LOC, SUM(LDS) as LDS, SUM(WT) as TONS from
           (select c.DATE_INDEX, c.VEH_LOC, COUNT(j.LOAD_JOB_ID) as LDS,
                 CASE WHEN SUM(w.SPOT_WEIGHT) = 0 THEN SUM(j.MAN_SPOT_WT)
                      ELSE SUM(w.SPOT_WEIGHT)
                  END as WT
              from TC c, TC_LOAD_JOBS j, LOAD_RATES r, SPOT_WEIGHTS w
             where c.TC_ID = j.TC_ID and j.LOAD_RATE_ID = r.LOAD_RATE_ID
               and c.DATE_INDEX = w.DATE_INDEX and j.LOAD_RATE_ID = w.LOAD_RATE_ID
               and c.VEH_LOC in (select ORG_ID from ORG_ENTITIES where MNG_ORG_ID = 200)
               and c.DATE_INDEX between to_date('08/01/2010','MM/DD/YYYY') and to_date('07/31/2011','MM/DD/YYYY')
             group by c.DATE_INDEX, c.VEH_LOC
            union
            select c.DATE_INDEX, c.VEH_LOC, COUNT(j.JOB_ID) as LDS,
                 DECODE(SUM(j.AVG_SPOT_WEIGHT),0,SUM(r.BID_TONS),SUM(j.AVG_SPOT_WEIGHT)) as WT
              from TC_3RDPARTY c, TC_3RDPARTY_JOBS j, LOAD_RATES r
             where c.TC_ID = j.TC_ID and j.LOAD_RATE_ID = r.LOAD_RATE_ID
               and c.DATE_INDEX between to_date('08/01/2010','MM/DD/YYYY') and to_date('07/31/2011','MM/DD/YYYY')
               and j.FACTORY_ID in (select ORG_ID from ORG_ENTITIES where MNG_ORG_ID = 200)
             group by c.DATE_INDEX, c.VEH_LOC)
          group by DATE_INDEX, VEH_LOC)
      group by DATE_INDEX)Now I need to add in the following query:
    select (u.MACH_TPH_D+u.MACH_TPH_N)/2 as MTPH_TGT, (u.LABOR_TPH_D+u.LABOR_TPH_N)/2 as LTPH_TGT
         from UTIL_TARGET_LOADERS u
        where u.ORG_ID in (select ORG_ID from ORG_ENTITIES where MNG_ORG_ID = 200)The join needs to be based on VEH_LOC and DAY in the form:
       ... WHERE u.ORG_ID = x.VEH_LOC
              AND x.DATE_INDEX between u.START_DATE and NVL(u.END_DATE,sysdate)I had one that worked just fine when only one entity was involved; the complication arises in that this is a division-level report so I have to individually resolve the subordinates and their goals before I can aggregate. This is one of two queries I need to tie together using a WITH clause so I can pivot the whole thing and present it in month-by-month fashion. When I try to tie it together like the query below, I get: invalid relational operator.
    select ttls.DATE_INDEX, SUM(ttls.LDS) as TTLLDS, SUM(ttls.TONS) as TTLTONS, u.TARGET_LTPH, u.TARGET_MTPH
      from UTIL_TARGET_LOADERS u,
        (select DATE_INDEX, VEH_LOC, SUM(LDS) as LDS, SUM(WT) as TONS from
           (select c.DATE_INDEX, c.VEH_LOC, COUNT(j.LOAD_JOB_ID) as LDS,
                 CASE WHEN SUM(w.SPOT_WEIGHT) = 0 THEN SUM(j.MAN_SPOT_WT)
                      ELSE SUM(w.SPOT_WEIGHT)
                  END as WT
              from TC c, TC_LOAD_JOBS j, LOAD_RATES r, SPOT_WEIGHTS w
             where c.TC_ID = j.TC_ID and j.LOAD_RATE_ID = r.LOAD_RATE_ID
               and c.DATE_INDEX = w.DATE_INDEX and j.LOAD_RATE_ID = w.LOAD_RATE_ID
               and c.VEH_LOC in (select ORG_ID from ORG_ENTITIES where MNG_ORG_ID = 200)
               and c.DATE_INDEX between to_date('08/01/2010','MM/DD/YYYY') and to_date('07/31/2011','MM/DD/YYYY')
             group by c.DATE_INDEX, c.VEH_LOC
            union
            select c.DATE_INDEX, c.VEH_LOC, COUNT(j.JOB_ID) as LDS,
                 DECODE(SUM(j.AVG_SPOT_WEIGHT),0,SUM(r.BID_TONS),SUM(j.AVG_SPOT_WEIGHT)) as WT
              from TC_3RDPARTY c, TC_3RDPARTY_JOBS j, LOAD_RATES r
             where c.TC_ID = j.TC_ID and j.LOAD_RATE_ID = r.LOAD_RATE_ID
               and c.DATE_INDEX between to_date('08/01/2010','MM/DD/YYYY') and to_date('07/31/2011','MM/DD/YYYY')
               and j.FACTORY_ID in (select ORG_ID from ORG_ENTITIES where MNG_ORG_ID = 200)
             group by c.DATE_INDEX, c.VEH_LOC)
          group by DATE_INDEX, VEH_LOC) ttls
        where ttls.DATE_INDEX beween u.START_DATE and NVL(u.END_DATE,sysdate)
          and ttls.VEH_LOC = u.ORG_ID
      group by ttls.DATE_INDEXI know this is a nested mess, as it has to grab the production from two tables for a range of VEH_LOC values and sum and aggregate by day and VEH_LOC, then I have to try and match that to the targets based on VEH_LOC and day. My final query is to aggregate the whole mess of sums and averages by month.
    I'd appreciate it if someone can point me in the right direction.

    Figured it out.
    select ttl.DATE_INDEX, SUM(ttl.LDS) as TTLLDS, SUM(ttl.TONS) as TTLTONS,
         AVG((u.MACH_TPH_D+u.MACH_TPH_N)/2) as MTPH_TGT,
         AVG((u.LABOR_TPH_D+u.LABOR_TPH_N)/2) as LTPH_TGT
      from
        (select DATE_INDEX, VEH_LOC, SUM(LDS) as LDS, SUM(WT) as TONS from
           (select c.DATE_INDEX, c.VEH_LOC, COUNT(j.LOAD_JOB_ID) as LDS,
                 CASE WHEN SUM(w.SPOT_WEIGHT) = 0 THEN SUM(j.MAN_SPOT_WT)
                      ELSE SUM(w.SPOT_WEIGHT)
                  END as WT
              from TC c, TC_LOAD_JOBS j, LOAD_RATES r, SPOT_WEIGHTS w
             where c.TC_ID = j.TC_ID and j.LOAD_RATE_ID = r.LOAD_RATE_ID
               and c.DATE_INDEX = w.DATE_INDEX and j.LOAD_RATE_ID = w.LOAD_RATE_ID
               and c.VEH_LOC in (select ORG_ID from ORG_ENTITIES where MNG_ORG_ID = 200)
               and c.DATE_INDEX between to_date('08/01/2010','MM/DD/YYYY') and to_date('07/31/2011','MM/DD/YYYY')
             group by c.DATE_INDEX, c.VEH_LOC
            union
            select c.DATE_INDEX, c.VEH_LOC, COUNT(j.JOB_ID) as LDS,
                 DECODE(SUM(j.AVG_SPOT_WEIGHT),0,SUM(r.BID_TONS),SUM(j.AVG_SPOT_WEIGHT)) as WT
              from TC_3RDPARTY c, TC_3RDPARTY_JOBS j, LOAD_RATES r
             where c.TC_ID = j.TC_ID and j.LOAD_RATE_ID = r.LOAD_RATE_ID
               and c.DATE_INDEX between to_date('08/01/2010','MM/DD/YYYY') and to_date('07/31/2011','MM/DD/YYYY')
               and j.FACTORY_ID in (select ORG_ID from ORG_ENTITIES where MNG_ORG_ID = 200)
             group by c.DATE_INDEX, c.VEH_LOC)
          group by DATE_INDEX, VEH_LOC) ttl, UTIL_TARGET_LOADERS u
      where u.ORG_ID = ttl.VEH_LOC
        and ttl.DATE_INDEX between u.START_DATE and NVL(U.END_DATE,sysdate)
      group by ttl.DATE_INDEX, (u.LABOR_TPH_D+u.LABOR_TPH_N)/2

  • Creating a complex query in CR designer

    I'm running Crystal Reports XI Release 2 on Windows NT. I have a very complex query and cannot figure out how to make it work in CR. Basically, I've got a table A with fields containing reference codes that may or may not be present. I created a SQL query that imbeds select statements in the select fields (the field names between SELECT and FROM). So, it would read something like SELECT field1, field2, (select Code_Name from REF_Table where REF_Table.code=TableA.code and TableA.code is not null) FROM TableA. That works great in SQL Developer.
    In CR, I tried a command field but that produces a cartesian set where I get a line for every record that has the field for each and every record in TableA.  No good. I just want the name for the value in the TableA record translated to the name if it is present.  Is there a way to do this in CR? I used to be able to edit the SQL directly in CR but now it won't let me do that. Anyone know a better way to solve this kind of problem?

    I'm not an Oracle guy so I don't know what you can or can't do in PL SQL.
    I'm surprised that you are getting different results between SQL Developer and the CR Command. CR should pass the query, exactly as it's written back to the server, same as SQL Dev.
    IN T-SQL...If  you want to make sure that the sub-query is returning only 1 row, try placing "TOP 1" behind the SELECT.
    (select top 1 loc.location_name
    from ref_location loc
    where loc.location_num=obd.location_num and odb.location_num is not null)
    I'm thinking that Oracle doesn't have the the TOP N option but it does have a rownum feature. So maybe...
    (SELECT x.location_name
    FROM (
        select loc.location_name
        from ref_location loc
        where loc.location_num=obd.location_num and odb.location_num is not null) x
    WHERE rownum = 1
    ORDER BY rownum)
    This is assuming that Oracle allows you to use ORDER BY in a sub-query. T-SQL only allows it if it's used in conjunction with TOP N...
    Just a thought,
    Jason

  • EJB for complex query

    Hi,
    I'm new in Enterprise javabeans, I have been looking for (almost five days) the
    best way to get the result for a complex query. I tried with example Weblogic
    BeanManaged. I put the query directly in a method in entityBean class with prepareStatament
    and that worked.
    But, I have to evaluate the best way to get result with EJB's. So, I think that
    I have to evaluate others like containerManaged, in this case I have to define
    each entity Bean and relationships and everything, isn't it?
    Is there another way to develop it with good results? and fast?
    If someone have any good idea to develop a solution with EJB's for this query.
    I'm really appreciate it.
    select CU.ID_CUENTA_USO, C.CLASE_CUENTA, C.ESTADO, P.ID_PRODUCTO, P.NOMBRE_PRODUCTO,
    CU.ID_TIPO_PAGO, AOA.ID_AREA, AOA.NOMBRE_AREA, AOA.ID_TIPO_AOA, CU.ID_CLIENTE_USUARIO,
    decode (PN.ID_PERSONA,null, decode (PJ.ID_PERSONA,null, PR.APELLIDOS || ' ' ||PR.NOMBRES,
    PJ.NOMBRE_EMPRESA),PN.APELLIDOS || ' ' ||PN.NOMBRES)
    from ATRIBUTOS A, CUENTA_USO CU, CUENTA C, PRODUCTO P,
    AREA_OPERACIONES_ADM AOA, PERSONA_NATURAL PN, PERSONA_JURIDICA PJ, PERSONA_REPRESENTADO
    PR
    where A.ABREVT_ATRIB_CTA_USO = 'NRO_CELULAR'
    and A.VALOR = '142000000'
    and CU.ID_CUENTA_USO = A.ID_CUENTA_USO
    and C.ID_CUENTA = CU.ID_CUENTA_USO
    and P.ID_PRODUCTO = CU.ID_PRODUCTO
    and AOA.ID_AREA(+) = CU. ID_AREA_ACTIVACION
    and AOA.ID_TIPO_AOA(+) = CU.ID_TIPO_AREA_ACTIVACION
    and PN.ID_PERSONA(+) = CU.ID_CLIENTE_USUARIO
    and PJ.ID_PERSONA(+) = CU.ID_CLIENTE_USUARIO
    and PR.ID_PERSONA(+) = CU.ID_CLIENTE_USUARIO
    order
    by P.ID_PRODUCTO, CU.ID_CUENTA_USO;
    Thank's in advanced
    Yose

    Hola/Hello Ryan
    Muchas Gracias por tu respuesta/ Thank's a lot for your answer, I'm trying with
    relationship-caching but something is missing.. because i got an error:
    ejbc:
    [java] [EJBCompiler] : Recompiling because no previous hashes found
    [java] [EJBCompiler] : Compliance Checker said bean was compliant
    [java]
    [java]
    [java]
    [java] ERROR: Error from ejbc: While reading META-INF/weblogic-cmp-rdbms-jar.xml,
    the Entity EJB's peristence layer failed to deploy. The error was:
    [java] Error in descriptor line 44: Element type "relationship-caching"
    must be declared.
    [java]
    [java]
    [java] ERROR: ejbc found errors
    I have two EJB Cuenta and Atributo I defined a relationship in the weblogic-cmp-rdbms-jar.
    (I want to start with two entity and add later the others producto, cuenta, persona_x)
    <relationship-caching>
         <caching-name>Cuenta-Atributo</caching-name>
         <caching-element>
              <cmr-field>cuenta</cmr-field>
              <group-name>cuentas_group</group-name>
              <caching-element>
                   <cmr-field>atributos</cmr-field>
                   <group-name>atrib_group</group-name>
              </caching-element>
         </caching-element>
    </relationship-caching>
    Where i have to defined it? Thanks a lot for your help..
    Yosemarlyn
    "Ryan LeCompte" <[email protected]> wrote:
    >
    Hola/Hello Yosemarlyn,
    You can utilize EJB 2.0 CMP to model the query that you specified. You
    would model
    the business domain as CMP Entity beans and then specify the various
    relationships
    among them. You actually may get an increase in performance by utilizing
    CMP/CMR
    in WebLogic due to the new features such as relationship caching, optimistic
    concurrency
    strategy support, etc. Utilizing these features will drastically reduce
    the number
    of SQL Joins (and overall hits to the database, due to caching). Below
    are various
    links for learning more:
    Mastering EJB II (Good book for learning about CMP/CMR):
    http://www.theserverside.com/books/masteringEJB/index.jsp
    Optimistic Concurrency:
    http://dev2dev.bea.com/resourcelibrary/technicalguides/Optimistic_Concurrency.jsp
    http://edocs.bea.com/wls/docs70/ejb/EJB_environment.html#1153757
    Relationship caching:
    http://edocs.bea.com/wls/docs70/ejb/EJB_environment.html#1151177
    Espero que esto te sirva bien. :-)
    Saludos,
    Ryan LeCompte
    [email protected]
    http://www.louisiana.edu/~rml7669
    "Yosemarlyn Lopez" <[email protected]> wrote:
    Hi,
    I'm new in Enterprise javabeans, I have been looking for (almost five
    days) the
    best way to get the result for a complex query. I tried with example
    Weblogic
    BeanManaged. I put the query directly in a method in entityBean class
    with prepareStatament
    and that worked.
    But, I have to evaluate the best way to get result with EJB's. So, I
    think that
    I have to evaluate others like containerManaged, in this case I have
    to define
    each entity Bean and relationships and everything, isn't it?
    Is there another way to develop it with good results? and fast?
    If someone have any good idea to develop a solution with EJB's for this
    query.
    I'm really appreciate it.
    select CU.ID_CUENTA_USO, C.CLASE_CUENTA, C.ESTADO, P.ID_PRODUCTO, P.NOMBRE_PRODUCTO,
    CU.ID_TIPO_PAGO, AOA.ID_AREA, AOA.NOMBRE_AREA, AOA.ID_TIPO_AOA, CU.ID_CLIENTE_USUARIO,
    decode (PN.ID_PERSONA,null, decode (PJ.ID_PERSONA,null, PR.APELLIDOS
    || ' ' ||PR.NOMBRES,
    PJ.NOMBRE_EMPRESA),PN.APELLIDOS || ' ' ||PN.NOMBRES)
    from ATRIBUTOS A, CUENTA_USO CU, CUENTA C, PRODUCTO P,
    AREA_OPERACIONES_ADM AOA, PERSONA_NATURAL PN, PERSONA_JURIDICA PJ, PERSONA_REPRESENTADO
    PR
    where A.ABREVT_ATRIB_CTA_USO = 'NRO_CELULAR'
    and A.VALOR = '142000000'
    and CU.ID_CUENTA_USO = A.ID_CUENTA_USO
    and C.ID_CUENTA = CU.ID_CUENTA_USO
    and P.ID_PRODUCTO = CU.ID_PRODUCTO
    and AOA.ID_AREA(+) = CU. ID_AREA_ACTIVACION
    and AOA.ID_TIPO_AOA(+) = CU.ID_TIPO_AREA_ACTIVACION
    and PN.ID_PERSONA(+) = CU.ID_CLIENTE_USUARIO
    and PJ.ID_PERSONA(+) = CU.ID_CLIENTE_USUARIO
    and PR.ID_PERSONA(+) = CU.ID_CLIENTE_USUARIO
    order
    by P.ID_PRODUCTO, CU.ID_CUENTA_USO;
    Thank's in advanced
    Yose
    [weblogic-cmp-rdbms-jar.xml]

  • Complex query design suggestions

    Hi, I should first of all point out I'm new to pl/sql and struggling a bit so any help you can provide is really appreciated.
    I have the requirements for a complex query the conditions of which are as follows
    Four tables involved
    ProductGroups, Products, Stock, StockMovements
    Query requirements psudeocode (broken into bits to make things easier)
    /* CODE */
    Select distinct products
    where productgroup.group between 'a' and 'z'
    And stock.location = 'x'
    And stock.qty > 0
    For each product
         _myDate = currentdate - 1 year
         stkMvt= Select * from StockMovements where product = product
         If(select count(*) from stkMvt where code = 'A' and type = 'A' and source = 'A' and stkMvt.date > _myDate) > 0)
              -- exclude row / move next product
         End If
         If (select count(*) from stkMvt where code = 'B' and type = 'B' and source = 'B' and stkMvt.date> _myDate) > 0)
              -- exclude row / move next product
         End If
         If (select count(*) from stkMvt where code = 'C' and type = 'C' and source = 'C' and Qty > 0 and stkMvt.date> _myDate) > 0)
              -- exclude row / move next product
         End If
         If (select max(stkMvt.date) from stkMvt where code = 'D' and type = 'D' and source = 'D' < _myDate)
              If ( select max(stkMvt.date) from stkMvt where ((code = 'E' and type = 'E' and source 'E')
                   Or (code = 'F' and type = 'F' and source = 'F')
                   Or (code = 'G' and type = 'G' and source = 'G')) > _myDate )
                   -- exclude row / move next product
              End If
         End If
         -- Get the fields to return
         Qty1 = Select coalesce(sum(qty),0) from stkMvt where code = 'H' and type = 'H' and source = 'H'
         Qty2 = Select coalesce(sum(qty),0) from stkMvt where code = 'I' and type = 'I' and source = 'I'
         Qty3 = Select coalesce(sum(qty),0) from stkMvt where code = 'J' and type = 'J' and source = 'J' and stkMvt.date between :fromDate and :toDate
         LastDate = Select max(stkMvt.Date) from stkMvt
         StkQty = Select Qty from Stock where product = product
         AllQty = Select AllQty from Stock where product = product
         FreeQty = StkQty - AllQty
         Value = Select value from Stock
         Select group, product , Qty1, Qty2, Qty3, LastDate, StkQty, AllQty, FreeQty, Value INTO table/cursor
    Loop
    Return table / cursor
    /* CODE END */
    Any guidance about the best way to achieve the above in an SP or Package would be massively helpful,
    Thanks in advance
    Scott.

    Agreed, it is a mess and I was looking the other way when it was dumped into my lap to deal with unfortunately. Any pointers in the right direction would really be helping me out.
    ok first the table structures, I'll include only the relevant fields to make things a bit easier.
    CREATE TABLE "TEST"."CMGROUP"
    (     "CMGRP_GROUP" CHAR(4 BYTE),
         "CMGRP_DESC" CHAR(30 BYTE)
    CREATE TABLE "TEST"."CMPROD"
    (     "CMP_PRODUCT" CHAR(20 BYTE),
         "CMP_DESC" CHAR(50 BYTE),
         "CMP_GROUP" CHAR(4 BYTE),
         "CMP_SPECIAL" CHAR(1 BYTE)
    CREATE TABLE "TEST"."STOCK"
         "STK_PRODUCT" CHAR(20 BYTE),
         "STK_LOC" CHAR(5 BYTE),
         "STK_STKQTY" NUMBER,
         "STK_VALUE" NUMBER,
         "STK_ALLSTK" NUMBER
    CREATE TABLE "TEST"."STMOVE"
         "STMOV_LOC" CHAR(5 BYTE),
         "STMOV_PRODUCT" CHAR(20 BYTE),
         "STMOV_DATE" DATE,
         "STMOV_TYPE" CHAR(1 BYTE),
         "STMOV_SOURCE" CHAR(1 BYTE),
         "STMOV_CODE" CHAR(1 BYTE),
         "STMOV_QTY" NUMBER,
         "STMOV_YEAR" NUMBER(5,0),
         "STMOV_PERIOD" NUMBER(5,0)
    Relationships are as follows
    CMGROUP.CMGRP = CMPROD.CMP_GROUP (One to Many)
    CMPROD.CMP_PRODUCT = STOCK.STK_PRODUCT (One to Many)
    STOCK.STK_LOC = STMOVE.STMOV_LOC (Many to Many)
    STOCK.STK_PRODUCT = STMOVE.STMOV_PRODUCT (Many to Many)
    As for the requirements well they aren't straightforward but the gist of it is to return a ref cursor to a crystal report from an oracle package. The ref cursor is to contain the following
    select products that are
    1) In stock
    2) For a specific location
    3) In a range of product groups
    4) That either have a manual stock receipt movement within the last 12 months
    5) Or do not have the following stock movement within the last 12 months
         a. PO Receipt
         b. WO Receipt
         c. Stock Acquisition Receipt
    Of the results I need to
         1) Display the group
         2) Display the product
         3) Sum the Qty of WO Receipts from the 1st of the month (13 Months Ago) until today
         4) Sum the Qty of PO Receipts from the 1st of the month (13 Months Ago) until today
         5) Sum the Qty of Stock Transfers from the 1st of the month (13 Months Ago) until today
         6) Display the most recent stock movement date
         7) Display the current stock quantity
         8) Display the allocated stock quantity
         9) Display the available stock quantity
         10) Display the stock value
    Movement code definitions as follows     
    Manual Stock Receipt
    Stmov_type: O
    Stmov_source: J
    Stmov_code: G
    Purchase Order Goods Receipt
    Stmov_type: O
    Stmov_source: R
    Stmov_code: S
    Stock Requisition Receipt (Positive stmov_qty value)
    Stmov_type: G
    Stmov_source: J
    Stmov_code: L
    Stock Requisition Issue (Negative stmov_qty value)
    Stmov_type: G
    Stmov_source: J
    Stmov_code: L
    Manual Stock Issue to GL Account (Issue to workshop)
    Stmov_type: F
    Stmov_source: J
    Stmov_code: G
    Works order issue
    Stmov_type: F
    Stmov_source: W
    Stmov_code: G
    Works order receipt
    Stmov_type: 1
    Stmov_source: W
    Stmov_code: G
    There are a few other conditions and requirements but I think that covers the basics. If there is anything I've left out let me know and I do my best to provide.
    Thanks in advance
    Scott.

  • How can I make this complex query?

    I don’t know how can I do this complex query...
    I have the tables Customers, Vehicles and Models. A customer can have 0-N Vehicles and a vehicle have 1 Model.
    Customers: ID_Customer (PK), Name, LastName...
    Vehicles: ID_Vehicle (PK), ID_Customer, ID_Model, date_sale
    Models: ID_Modelo (PK), Model_Name
    Then I need to know the buy average time (date_sale) between 2 models (ID_Model)
    For example I have these Vehicles:
    ID_Vehicle (PK)...ID_Customer...ID_Model....date_sale
    1................................123....................1.............21/05/2000
    2................................459....................3............ 16/08/2000
    3................................123....................2............ 28/06/2001
    4................................516....................1............ 09/09/2001
    5................................459....................4............ 18/10/2002
    6................................516....................2............ 20/12/2002
    If I want to know the buy average time (date_sale) between ID_Model 1 and ID_Model 2 it is. (403 + 467) / 2 = 435 days !!!
    * Customer 123 (model 1 to 2): 25/06/2001 – 21/05/2000 ==> 403 days
    * Customer 516 (model 1 to 2): 01/12/2002 – 01/05/2000 ==> 467 days.
    I need to do the query for all the combination models. For example If I have the Models 1, 2 and 3 I need to obtain:
    Source_Model.....Target_Model....Buy_Average_Time
    1......................................1....................... xxx days
    1......................................2....................... xxx days
    1......................................3....................... xxx days
    2......................................1....................... xxx days
    2......................................2....................... xxx days
    2......................................3....................... xxx days
    3......................................1....................... xxx days
    3......................................2....................... xxx days
    3......................................3....................... xxx days
    If it is necessary I could create a table with the fields Source_Model, Target_Model and Buy_Average_Time for accelerate the query time response.
    But how can I do this query??????????
    Thanks very much!!!

    Hi,
    Thanks for your reply but It is not correct for me because the Customer could have several vehicles in her life.
    If I make the query with my examples data it is OK
    ID_Vehicle (PK)...ID_Customer...ID_Model....date_sale
    1................................123....................1.............21/05/2000
    2................................459....................3............ 16/08/2000
    3................................123....................2............ 28/06/2001
    4................................516....................1............ 09/09/2001
    5................................459....................4............ 18/10/2002
    6................................516....................2............ 20/12/2002
    select v1.id_model as source_model,
    v2.id_model as target_model,
    avg (v2.date_sale - v1.date_sale) || ' days' as buy_average_time
    from vehicles v1,
    vehicles v2
    where v1.id_customer = v2.id_customer
    and v2.date_sale > v1.date_sale
    group by v1.id_model, v2.id_model;
    I received:
    SOURCE_MODEL     TARGET_MODEL     BUY_AVERAGE_TIME
    ..............1................................2.....................................435 days
    ..............3................................4.....................................793 days
    But If I insert a new vehicle:
    ID_Vehicle (PK)...ID_Customer...ID_Model....date_sale
    7................................516....................3............ 16/08/2003
    And I execute the query now I receive:
    SOURCE_MODEL     TARGET_MODEL     BUY_AVERAGE_TIME
    ..............1................................2...........................435 days
    ..............1................................3...........................706 days
    ..............2................................3...........................239 days
    ..............3................................4...........................793 days
    It is NO correct because I don’t have the 1 (Source_model) to 3 (Target_model) combination in the Vehicles data!!! (I have 1 to 2 and 2 to 3 but NO 1 to 3!!!!).
    Then the query is not OK for me!
    Besides If I modify the Vehicle 7 data and put ID_Model = 2:
    ID_Vehicle (PK)...ID_Customer...ID_Model....date_sale
    7................................516....................2............ 16/08/2003
    I received:
    SOURCE_MODEL     TARGET_MODEL     BUY_AVERAGE_TIME
    ..............1................................2...........................525,33 days
    ..............2................................2...........................239 days
    ..............3................................4...........................793 days
    It is NO correct because the BUY_AVERAGE_TIME for 1 to 2 combination is 435 days (the same of the original query) because I aggregate only the combination 2 to 2 with the ID_VEHICLE 7
    Below I attach the examples scripts.
    Could you help me with this query, please?
    Thanks very much!
    CREATE TABLE VEHICLES
    ID_VEHICLE NUMBER(9),
    ID_CUSTOMER NUMBER(9),
    ID_MODEL NUMBER(9),
    DATE_SALE DATE
    TABLESPACE USERS
    PCTUSED 0
    PCTFREE 10
    INITRANS 1
    MAXTRANS 255
    STORAGE (
    INITIAL 64K
    MINEXTENTS 1
    MAXEXTENTS 2147483645
    PCTINCREASE 0
    BUFFER_POOL DEFAULT
    LOGGING
    NOCACHE
    NOPARALLEL;
    INSERT INTO VEHICLES ( ID_VEHICLE, ID_CUSTOMER, ID_MODEL, DATE_SALE ) VALUES (
    1, 123, 1, TO_Date( '05/21/2000 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'));
    INSERT INTO VEHICLES ( ID_VEHICLE, ID_CUSTOMER, ID_MODEL, DATE_SALE ) VALUES (
    2, 459, 3, TO_Date( '08/16/2000 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'));
    INSERT INTO VEHICLES ( ID_VEHICLE, ID_CUSTOMER, ID_MODEL, DATE_SALE ) VALUES (
    3, 123, 2, TO_Date( '06/28/2001 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'));
    INSERT INTO VEHICLES ( ID_VEHICLE, ID_CUSTOMER, ID_MODEL, DATE_SALE ) VALUES (
    4, 516, 1, TO_Date( '09/09/2001 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'));
    INSERT INTO VEHICLES ( ID_VEHICLE, ID_CUSTOMER, ID_MODEL, DATE_SALE ) VALUES (
    5, 459, 4, TO_Date( '10/18/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'));
    INSERT INTO VEHICLES ( ID_VEHICLE, ID_CUSTOMER, ID_MODEL, DATE_SALE ) VALUES (
    6, 516, 2, TO_Date( '12/20/2002 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'));
    INSERT INTO VEHICLES ( ID_VEHICLE, ID_CUSTOMER, ID_MODEL, DATE_SALE ) VALUES (
    7, 516, 2, TO_Date( '08/16/2003 12:00:00 AM', 'MM/DD/YYYY HH:MI:SS AM'));
    COMMIT;
    CREATE TABLE MODELS
    ID_MODELO NUMBER(9),
    MODEL_NAME VARCHAR2(25 BYTE)
    TABLESPACE USERS
    PCTUSED 0
    PCTFREE 10
    INITRANS 1
    MAXTRANS 255
    STORAGE (
    INITIAL 64K
    MINEXTENTS 1
    MAXEXTENTS 2147483645
    PCTINCREASE 0
    BUFFER_POOL DEFAULT
    LOGGING
    NOCACHE
    NOPARALLEL;
    INSERT INTO MODELS ( ID_MODELO, MODEL_NAME ) VALUES (
    1, 'MODEL 1');
    INSERT INTO MODELS ( ID_MODELO, MODEL_NAME ) VALUES (
    2, 'MODEL 2');
    INSERT INTO MODELS ( ID_MODELO, MODEL_NAME ) VALUES (
    3, 'MODEL 3');
    INSERT INTO MODELS ( ID_MODELO, MODEL_NAME ) VALUES (
    4, 'MODEL 4');
    COMMIT;
    CREATE TABLE CUSTOMERS
    ID_CUSTOMER NUMBER(9),
    NAME VARCHAR2(25 BYTE),
    LASTNAME VARCHAR2(25 BYTE)
    TABLESPACE USERS
    PCTUSED 0
    PCTFREE 10
    INITRANS 1
    MAXTRANS 255
    STORAGE (
    INITIAL 64K
    MINEXTENTS 1
    MAXEXTENTS 2147483645
    PCTINCREASE 0
    BUFFER_POOL DEFAULT
    LOGGING
    NOCACHE
    NOPARALLEL;
    INSERT INTO CUSTOMERS ( ID_CUSTOMER, NAME, LASTNAME ) VALUES (
    123, 'Customer 123', 'A');
    INSERT INTO CUSTOMERS ( ID_CUSTOMER, NAME, LASTNAME ) VALUES (
    459, 'Customer 459', 'B');
    INSERT INTO CUSTOMERS ( ID_CUSTOMER, NAME, LASTNAME ) VALUES (
    516, 'Customer 516', 'C');
    INSERT INTO CUSTOMERS ( ID_CUSTOMER, NAME, LASTNAME ) VALUES (
    318, 'Customer 318', 'D');
    COMMIT;

  • Complex Query which needs tuning

    Hello :
    I have a complex query that needs to be tuned. I have little experience in tuning the sql and hence taking the help of your guys.
    The Query is as given below:
    Database version 11g
    SELECT DISTINCT P.RESPONSIBILITY, P.PRODUCT_MAJOR, P.PRODUCT_MINOR,
    P.PRODUCT_SERIES, P.PRODUCT_CATEGORY AS Category1, SO.REGION_CODE,
    SO.STORE_CODE, S.Store_Name, SOL.PRODUCT_CODE, PRI.REPLENISHMENT_TYPE,
    PRI.SUPPLIER_CODE,
    SOL.SOLD_WITH_NIC, SOL.SUGGESTED_PRICE,
    PRI.INVOICE_COST, SOL.FIFO_COST,
    SO.ORDER_TYPE_CODE, SOL.DOCUMENT_NUM,
    SOS.SLSP_CD, '' AS FNAME, '' AS LNAME,
    SOL.PRICE_EXCEPTION_CODE, SOL.AS_IS,
    SOL.STATUS_DATE,
    Sum(SOL.QUANTITY) AS SumOfQUANTITY,
    Sum(SOL.EXTENDED_PRICE) AS SumOfEXTENDED_PRICE
    --Format([SALES_ORDER].[STATUS_DATE],"mmm-yy") AS [Month]
    FROM PRODUCT P,
    PRODUCT_MAJORS PM,
    SALES_ORDER_LINE SOL,
    STORE S,
    SALES_ORDER SO,
    SALES_ORDER_SPLITS SOS,
    PRODUCT_REGIONAL_INFO PRI,
    REGION_MAP R
    WHERE P.product_major = PM.PRODUCT_MAJOR
    and SOL.PRODUCT_CODE = P.PRODUCT_CODE
    and SO.STORE_CODE = S.STORE_CODE
    AND SO.REGION_CODE = S.REGION_CODE
    AND SOL.REGION_CODE = SO.REGION_CODE
    AND SOL.DOCUMENT_NUM = SO.DOCUMENT_NUM
    AND SOL.DELIVERY_SEQUENCE_NUM = SO.DELIVERY_SEQUENCE_NUM
    AND SOL.STATUS_CODE = SO.STATUS_CODE
    AND SOL.STATUS_DATE = SO.STATUS_DATE
    AND SO.REGION_CODE = SOS.REGION_CODE
    AND SO.DOCUMENT_NUM = SOS.DOCUMENT_NUM
    AND SOL.PRODUCT_CODE = PRI.PRODUCT_CODE
    AND PRI.REGION_CODE = R.CORP_REGION_CODE
    AND SO.REGION_CODE = R.DS_REGION_CODE
    AND P.PRODUCT_MAJOR In ('STEREO','TELEVISION','VIDEO')
    AND SOL.STATUS_CODE = 'D'
    AND SOL.STATUS_DATE BETWEEN '01-JUN-09' AND '30-JUN-09'
    AND SO.STORE_CODE NOT IN
    ('10','20','30','40','70','91','95','93','94','96','97','98','99',
    '9V','9W','9X','9Y','9Z','8Z',
    '8Y','92','CZ','FR','FS','FT','FZ','FY','FX','FW','FV','GZ','GY','GU','GW','GV','GX')
    GROUP BY
    P.RESPONSIBILITY, P.PRODUCT_MAJOR, P.PRODUCT_MINOR, P.PRODUCT_SERIES, P.PRODUCT_CATEGORY,
    SO.REGION_CODE, SO.STORE_CODE, /*S.Short Name, */
    S.Store_Name, SOL.PRODUCT_CODE,
    PRI.REPLENISHMENT_TYPE, PRI.SUPPLIER_CODE,
    SOL.SOLD_WITH_NIC, SOL.SUGGESTED_PRICE, PRI.INVOICE_COST,
    SOL.FIFO_COST, SO.ORDER_TYPE_CODE, SOL.DOCUMENT_NUM,
    SOS.SLSP_CD, '', '', SOL.PRICE_EXCEPTION_CODE,
    SOL.AS_IS, SOL.STATUS_DATE
    Explain Plan:
    SELECT STATEMENT, GOAL = ALL_ROWS               Cost=583     Cardinality=1     Bytes=253
    HASH GROUP BY               Cost=583     Cardinality=1     Bytes=253
    FILTER                         
    NESTED LOOPS               Cost=583     Cardinality=1     Bytes=253
    HASH JOIN OUTER               Cost=582     Cardinality=1     Bytes=234
    NESTED LOOPS                         
    NESTED LOOPS               Cost=571     Cardinality=1     Bytes=229
    NESTED LOOPS               Cost=571     Cardinality=1     Bytes=207
    NESTED LOOPS               Cost=569     Cardinality=2     Bytes=368
    NESTED LOOPS               Cost=568     Cardinality=2     Bytes=360
    NESTED LOOPS               Cost=556     Cardinality=3     Bytes=435
    NESTED LOOPS     Cost=178     Cardinality=4     Bytes=336
    NESTED LOOPS          Cost=7     Cardinality=1     Bytes=49
    HASH JOIN               Cost=7     Cardinality=1     Bytes=39
    VIEW     Object owner=CORP     Object name=index$_join$_015     Cost=2     Cardinality=3     Bytes=57
    HASH JOIN                         
    INLIST ITERATOR                         
    INDEX UNIQUE SCAN     Object owner=CORP     Object name=PRODMJR_PK     Cost=0     Cardinality=3     Bytes=57
    INDEX FAST FULL SCAN     Object owner=CORP     Object name=PRDMJR_PR_FK_I     Cost=1     Cardinality=3     Bytes=57
    VIEW     Object owner=CORP     Object name=index$_join$_016     Cost=4     Cardinality=37     Bytes=740
    HASH JOIN                         
    INLIST ITERATOR                         
    INDEX RANGE SCAN     Object owner=CORP     Object name=PRDMNR1     Cost=3     Cardinality=37     Bytes=740
    INDEX FAST FULL SCAN     Object owner=CORP     Object name=PRDMNR_PK     Cost=4     Cardinality=37     Bytes=740
    INDEX UNIQUE SCAN     Object owner=CORP     Object name=PRODMJR_PK     Cost=0     Cardinality=1     Bytes=10
    MAT_VIEW ACCESS BY INDEX ROWID     Object owner=CORP     Object name=PRODUCTS     Cost=171     Cardinality=480     Bytes=16800
    INDEX RANGE SCAN     Object owner=CORP     Object name=PRD2     Cost=3     Cardinality=681     
    TABLE ACCESS BY INDEX ROWID     Object owner=DS     Object name=SALES_ORDER_LINE     Cost=556     Cardinality=1     Bytes=145
    BITMAP CONVERSION TO ROWIDS                         
    BITMAP INDEX SINGLE VALUE     Object owner=DS     Object name=SOL2               
    TABLE ACCESS BY INDEX ROWID     Object owner=DS     Object name=SALES_ORDER     Cost=4     Cardinality=1     Bytes=35
    INDEX RANGE SCAN     Object owner=DS     Object name=SO1     Cost=3     Cardinality=1     
    TABLE ACCESS BY INDEX ROWID     Object owner=DS     Object name=REGION_MAP     Cost=1     Cardinality=1     Bytes=4
    INDEX RANGE SCAN     Object owner=DS     Object name=REGCD     Cost=0     Cardinality=1     
    MAT_VIEW ACCESS BY INDEX ROWID     Object owner=CORP     Object name=PRODUCT_REGIONAL_INFO     Cost=2     Cardinality=1     Bytes=23
    INDEX UNIQUE SCAN     Object owner=CORP     Object name=PRDRI_PK     Cost=1     Cardinality=1     
    INDEX UNIQUE SCAN     Object owner=CORP     Object name=BI_STORE_INFO_PK     Cost=0     Cardinality=1     
    MAT_VIEW ACCESS BY INDEX ROWID     Object owner=CORP     Object name=BI_STORE_INFO     Cost=1     Cardinality=1     Bytes=22
    VIEW     Object owner=DS     cost=11     Cardinality=342     Bytes=1710
    HASH JOIN               Cost=11     Cardinality=342     Bytes=7866
    MAT_VIEW ACCESS FULL     Object owner=CORP     Object name=STORE_CORP     Cost=5     Cardinality=429     Bytes=3003
    NESTED LOOPS               Cost=5     Cardinality=478     Bytes=7648
    MAT_VIEW ACCESS FULL     Object owner=CORP     Object name=STORE_GROUP     Cost=5     Cardinality=478     Bytes=5258
    INDEX UNIQUE SCAN     Object owner=CORP     Object name=STORE_REGIONAL_INFO_PK     Cost=0     Cardinality=1     Bytes=5
    INDEX RANGE SCAN     Object owner=DS     Object name=SOS_PK     Cost=2     Cardinality=1     Bytes=19
    Regards,
    BMP

    First thing that i notice in this query is you are Using Distinct as well as Group by.
    Your group by will always give you distinct results ,then again why do you need the Distinct?
    For example
    WITH t AS
         (SELECT 'clm1' col1, 'contract1' col2,10 value
            FROM DUAL
          UNION ALL
          SELECT 'clm1' , 'contract1' ,10 value
            FROM DUAL
          UNION ALL
          SELECT 'clm1', 'contract2',10
            FROM DUAL
          UNION ALL
          SELECT 'clm2', 'contract1',10
            FROM DUAL
          UNION ALL
          SELECT 'clm3', 'contract1',10
            FROM DUAL
          UNION ALL
          SELECT 'clm4', 'contract2',10
            FROM DUAL)
    SELECT  distinct col1,col2,sum(value) from t
    group by col1,col2Is always same as
    WITH t AS
         (SELECT 'clm1' col1, 'contract1' col2,10 value
            FROM DUAL
          UNION ALL
          SELECT 'clm1' , 'contract1' ,10 value
            FROM DUAL
          UNION ALL
          SELECT 'clm1', 'contract2',10
            FROM DUAL
          UNION ALL
          SELECT 'clm2', 'contract1',10
            FROM DUAL
          UNION ALL
          SELECT 'clm3', 'contract1',10
            FROM DUAL
          UNION ALL
          SELECT 'clm4', 'contract2',10
            FROM DUAL)
    SELECT  col1,col2,sum(value) from t
    group by col1,col2And also
    AND SOL.STATUS_DATE BETWEEN '01-JUN-09' AND '30-JUN-09'It would be best to use a to_date when hard coding your dates.
    Edited by: user5495111 on Aug 6, 2009 1:32 PM

  • EJB-QL---  Complex Query --- Two Entites

    hi
    Can i write Complex Query in EJB-QL
    between two entities...
    have any buddy wrote the same....
    i badly require the same...
    bye
    RAJ

    Raj -- OC4J will support EJB-QL soon but not yet. You can look at
    Re: Data Integrity
    for more details.
    Now, as for complex query, you may still be able to do this in the current version through the orion-ejb-jar.xml. You can
    include complex SQL there in the finder methods.
    What exactly do you need to do?
    later -- Jeff
    hi
    Can i write Complex Query in EJB-QL
    between two entities...
    have any buddy wrote the same....
    i badly require the same...
    bye
    RAJ

  • Slow tabbing between fields

    Hello,
    We have a very complex interactive form with repeating_subforms. We open it binding a large xml file. Tabbing between fields is very slow when we are editing the form.
    We have designed a simple form with one repeating_subform and without scripting. Bindig the same xml file, tabbing between fields is very slow too.
    How can we solve this problem?
    Here are the links to pdf file and to xdp file with the data.
    Thanking you in advance,

    Thank you for answering!
    We are using Livecycle Designer ES4 v 11.0.1 and Acrobat XI pro.

  • Need help: GUI_DOWNLOAD and tab-separated in between fields.

    hello everyone,
    this is the layout of the interface that i created:
             sy-title
    total records processed: XX
    total records failed: XX
    summary of the error
    pernr<tab>name<tab>error message<tab>otherfieldshere
    i wanted the error log to be saved locally thus, i have to use GUI_DOWNLOAD.
    ok, here's the current parameters i supplied with my gui_download:
    CALL FUNCTION 'GUI_DOWNLOAD'
           EXPORTING
                filename                    = v_file_string
                filetype                      = 'ASC'
                write_field_separator   = 'X'
           TABLES
                data_tab                    = i_error_log
    (exceptions not displayed)
    the problem that i have is that, there is a difference between the error logs displayed after the execution and the error logs saved in my local directory.
    i did find a way to resolve this BUT, i still need to refine it. also, the spaces between the fields seems not tab delimited, but separated by space.
    to explain further here's the current error log that i have downloaded:
    10000001<tab>10/23/2006<tab>01<tab>P<tab>11<tab>01
    the header:
             sy-title
    total records processed: XX
    total records failed: XX
    summary of the error
    is not included in the downloaded errorlog file.
    i added some modification of my report to include it because, i want to to look exactly the same as of the errorlog generated/displyed after the execution.
    the result looks as it is what i've expected BUT,
    when i checked the spaces in between fields...
    it is all separated by spaces... not tab.
    here is the actual error log that i have obtained:
             sy-title
    total records processed: XX
    total records failed: XX
    summary of the error
    pernr<space><space><space>name<space><space><space><space><space><space>error message<space><space>otherfieldshere
    What i wanted to resolve is that, i want the error log to be tab delimited and not separated by space.
    is this possible? if it is, any suggestion will truly be appreciated.

    Hi,
    Please check your flat file i think it they have used the Three spaces instead of using a SINGLE TAB. between the fields.
    Thanks & Regards,
    Chandralekha.

  • How to create an explain plan with rowsource statistics for a complex query that include multiple table joins ?

    1. How to create an explain plan with rowsource statistics for a complex query that include multiple table joins ?
    When multiple tables are involved , and the actual number of rows returned is more than what the explain plan tells. How can I find out what change is needed  in the stat plan  ?
    2. Does rowsource statistics gives some kind of  understanding of Extended stats ?

    You can get Row Source Statistics only *after* the SQL has been executed.  An Explain Plan midway cannot give you row source statistics.
    To get row source statistics either set STATISTICS_LEVEL='ALL'  in the session that executes theSQL OR use the Hint "gather_plan_statistics"  in the SQL being executed.
    Then use dbms_xplan.display_cursor
    Hemant K Chitale

  • Sap query and additional fields.

    Hello guys.
    ABAP it's not my strong skill, but i need to develop some report.
    What i need:
    input: material, SLED, plant
    output: material, SLED, plant, values from characteristic field.
    I have created sap query with additional field type c.
    Below my code:
    TYPES: BEGIN OF charast,
            ATNAM(50)    TYPE c,
            ATWTB(8)     TYPE n,
            X(50)        TYPE n,
            C(50)        TYPE n,
            ATINN(50)    TYPE n,
            END OF charast.
    DATA: char TYPE TABLE OF charast WITH HEADER LINE.
    CALL FUNCTION 'VB_BATCH_GET_DETAIL'
       EXPORTING
         MATNR              = MCH1-MATNR
         CHARG              = MCH1-CHARG
         GET_CLASSIFICATION = 'X'
       TABLES
         CHAR_OF_BATCH      = char.
    LOOP AT char into TEST (This is an additional field type C.
       ENDLOOP.
    Questions:
    1. How i can return internal table into standard abap type, because i can create additional field only with standart types.
    2. Need i fetch exporting parameters before calling FM? Or sap query do it automatically, based on given values on selection screen of the report?
    3. How i can return only needed field from FM output? Now, when i'm executing FM via SE37 it's show desired result, but when i'm getting it from code i see strange values.
    4. If i don't know exactly return by an FM values, how i can fill structure dynamically?
    5. How i can return result of a program not only to additional field but to layout?
    Sorry for noob questions and thank you in advance guys!

    Well, seems like it work fine for me.
    Below my crappy, but working code:
    DATA: material TYPE MCHB-MATNR,
           batch    TYPE MCHB-CHARG,
           plant    TYPE MCHB-WERKS,
           sloc     TYPE MCHB-LGORT,
           gtdt     TYPE STANDARD TABLE OF clbatch,
           gtdit    TYPE clbatch.
    SELECT MATNR INTO material FROM MCHB
       WHERE MATNR = MCHB-MATNR.
    ENDSELECT.
    SELECT CHARG INTO batch FROM MCHB
       WHERE CHARG = MCHB-CHARG.
    ENDSELECT.
    SELECT WERKS INTO plant FROM MCHB
       WHERE WERKS = MCHB-WERKS.
    ENDSELECT.
    SELECT LGORT INTO sloc FROM MCHB
       WHERE LGORT = MCHB-LGORT.
    ENDSELECT.
    CALL FUNCTION 'VB_BATCH_GET_DETAIL'
       EXPORTING
         MATNR = material
         CHARG = batch
         WERKS = plant
         GET_CLASSIFICATION = 'X'
        TABLES
          CHAR_OF_BATCH = gtdt.
    READ TABLE gtdt INTO gtdit
       WITH KEY atnam = 'BATCH_SHELF_LIFE_EXPIRY_DATE'.
    GTD = gtdit-ATWTB.

Maybe you are looking for