Complex query help

Hope someone can help with this.
I have a database structure :
table : photos
Photo_ID (PK)
Title
Orientation
etc
table : keywords
Keyword_ID (PK)
Keyword
Category
table : photokeywords
Photo_ID
Keyword_ID
I have a search page that uses checkboxes allowing users to
search on keywords, that returns any photos which match the
selected keywords.
In the search page the checkboxes are created using an array,
and are displayed as :
//Display the checkbox
echo "<td width=\"2%\">";
echo "<input type=\"checkbox\"
class=\"tickbox_".$row_type."\"";
if (in_array($keyword['Keyword_ID'],$photokeywords)) { echo
" checked"; }
echo " name=\"ckbox[".$keyword['Keyword_ID']."]\"
id=\"ckbox[".$keyword['Keyword_ID']."]\">";
echo "</td>\n";
Someone kindly helped me out some time ago to write a fairly
complex (for me!) query that counts the matches, so enabling the
results to be ordered by the number of matches, ie the most
relevant matches first.
The code for this is :
//db session
mysql_select_db($database_Photolibrary, $Photolibrary);
if (isset($_GET['ckbox'])){
// get profile keys
$ckbox = array_keys($_GET['ckbox']);
// sql string
$sql = 'SELECT *, Count(*) As rank FROM photos, photokeywords
WHERE photos.Photo_ID =
photokeywords.Photo_ID AND photokeywords.Keyword_ID IN(' .
implode(',', $ckbox).') GROUP BY
photos.Photo_ID ORDER BY rank DESC, Title';
$photos = mysql_query($sql) or die(mysql_error());
$row_photos = mysql_fetch_assoc($photos);
@$totalRows = mysql_num_rows($photos);
The page I have is using Tom Muck's pages list and horizontal
looper behaviours to display the results.
Everything works fine except the pages list, where there is
more than one page of results. I've emailed the ever helpful Tom
who has advised me that the query may need to be constructed in DW,
as the Pages List behaviour relies on DW's code to manage the
paging.
So I've gotten as far as the basic query code :
<?php
mysql_select_db($database_Photolibrary, $Photolibrary);
$query_photos = "SELECT *, Count(*) As rank FROM photos,
photokeywords WHERE photos.Photo_ID = photokeywords.Photo_ID AND
photokeywords.Keyword_ID IN(' . implode(',', $ckbox).') GROUP BY
photos.Photo_ID ORDER BY rank DESC, Title";
$photos = mysql_query($query_photos, $Photolibrary) or
die(mysql_error());
$row_photos = mysql_fetch_assoc($photos);
$totalRows_photos = mysql_num_rows($photos);
?>
But am unsure where I need to call the ckbox values,
previously :
if (isset($_GET['ckbox'])){
// get profile keys
$ckbox = array_keys($_GET['ckbox']);
in the DW construction.
I've been playing around with different things in the query's
variables, such as
Name : Keyword_ID
Default value : 1
Run time value : $_GET['ckbox']
but to no avail.
If anyone can help out with this it'd be much appreciated.
Cheers.

Something like this?
SQL> var P_DISCOUNT_RATE number
SQL> var P_BASE_YEAR number
SQL> var P_FUTURE_YEAR number
SQL> exec :P_DISCOUNT_RATE := 0.1; :P_BASE_YEAR := 2003; :P_FUTURE_YEAR := 2009;
PL/SQL-procedure is geslaagd.
SQL> select sum(npd)
  2    from ( select nvl
  3                  ( ( select sum(sal)
  4                        from emp
  5                       where to_number(to_char(hiredate,'yyyy')) + 25 = :P_FUTURE_YEAR - l
  6                    )
  7                  , 0
  8                  ) / power(1 + :P_DISCOUNT_RATE, l) npd
  9             from ( select level-1 l from dual connect by level <= 1 + :P_FUTURE_YEAR - :P_BASE_YEAR )
10         )
11  /
                              SUM(NPD)
22248,89010313503176012567447578717301
1 rij is geselecteerd.I counted 7 iterations for the values 2003 and 2009, so you might want to explain a little more.
Regards,
Rob.

Similar Messages

  • 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

  • Complex query

    I am novice in PL/Sql. I need some help in writing a complex query.
    I imagine the following table structure.
    Type(string) Date(date) count(int)
    Given a date range
    The query needs to group the records on type and return the record (type and count) which has the max date (its just date, no time is involved) for each group (which is based on type) . If there are more than one records which have the max date then the average count should be returned for that type
    i would be glad if someone could give any ideas as to how to go about this query. Thanking you in advance.
    regards.

    Heres the query ... Forget the period .... wht this query is supposed to do is group on assigned ki for a given date range. then it has to get the value which is for the last record for that Ki in the date range. If there are 2 records which have max date then it should give an average.
    e.g
    assignedKI / date / value
    a 1st may 2008 10
    b 2nd may 2008 12
    c 1st may 2008 13
    a 30 - apr-2008 16
    b 4th may 2008 17
    a 1st may 2008 20
    The query should return
    a 1st may 2008 15 (which is the average as there are 2 values for the max date for a)
    b 4th may 2008 17
    c 1st may 2008 13
    the following query doesnot work ....
    SELECT
    kiv2.assigned_k_i,
    kiv2.ki_name,
    kiv.period,
    max( kiv2.ki_value_date) ,
    avg(kiv2.ki_value)
    FROM
    SELECT
    assigned_k_i,
    period p1,
    TO_CHAR(ki_value_date, period) period,
    MAX(ki_value_date) ki_value_date
    FROM
    v_ki_value,
    (select ? period from dual)
         WHERE
         (status = 'APPROVED' OR status = 'AUTOAPPROVED')
    AND ( trunc(to_date(to_char(ki_value_date, 'DD/MM/YYYY'), 'DD/MM/YYYY')) >= ?)
    AND ( trunc(to_date(to_char(ki_value_date, 'DD/MM/YYYY'), 'DD/MM/YYYY')) &lt;= ?)
    AND (INSTR(?, TO_CHAR(assigned_k_i)) > 0)
    GROUP BY
    assigned_k_i,
    TO_CHAR(ki_value_date, period)
    ) kiv,
    v_ki_value kiv2
    WHERE
    kiv.assigned_k_i = kiv2.assigned_k_i
    AND to_char(kiv.ki_value_date, kiv.p1) = to_char(kiv2.ki_value_date, kiv.p1)
    GROUP BY
    kiv2.assigned_k_i,
    kiv2.ki_name,
    kiv.period,
    kiv2.ki_value
    ORDER BY
    kiv2.assigned_k_i

  • 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

  • Need complex query  with joins and AGGREGATE  functions.

    Hello Everyone ;
    Good Morning to all ;
    I have 3 tables with 2 lakhs record. I need to check query performance.. How CBO rewrites my query in materialized view ?
    I want to make complex join with AGGREGATE FUNCTION.
    my table details
    SQL> select from tab;*
    TNAME TABTYPE CLUSTERID
    DEPT TABLE
    PAYROLL TABLE
    EMP TABLE
    SQL> desc emp
    Name
    EID
    ENAME
    EDOB
    EGENDER
    EQUAL
    EGRADUATION
    EDESIGNATION
    ELEVEL
    EDOMAIN_ID
    EMOB_NO
    SQL> desc dept
    Name
    EID
    DNAME
    DMANAGER
    DCONTACT_NO
    DPROJ_NAME
    SQL> desc payroll
    Name
    EID
    PF_NO
    SAL_ACC_NO
    SALARY
    BONUS
    I want to make  complex query  with joins and AGGREGATE  functions.
    Dept names are : IT , ITES , Accounts , Mgmt , Hr
    GRADUATIONS are : Engineering , Arts , Accounts , business_applications
    I want to select records who are working in IT and ITES and graduation should be "Engineering"
    salary > 20000 and < = 22800 and bonus > 1000 and <= 1999 with count for males and females Separately ;
    Please help me to make a such complex query with joins ..
    Thanks in advance ..
    Edited by: 969352 on May 25, 2013 11:34 AM

    969352 wrote:
    why do you avoid providing requested & NEEDED details?I do NOT understand what do you expect ?
    My Goal is :
    1. When executing my own query i need to check expalin plan.please proceed to do so
    http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_9010.htm#SQLRF01601
    2. IF i enable query rewrite option .. i want to check explain plan ( how optimizer rewrites my query ) ? please proceed to do so
    http://docs.oracle.com/cd/E11882_01/server.112/e16638/ex_plan.htm#PFGRF009
    3. My only aim is QUERY PERFORMANCE with QUERY REWRITE clause in materialized view.It is an admirable goal.
    Best Wishes on your quest for performance improvements.

  • 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

  • Complex query crashing database!

    Hi
    Our 10g database runs on Windows 2003 (with 32 GB RAM on server).
    Whenever a user is running a particular complex query, the database just crashes suddenly.
    In fact, it doesn't write anything in alert log file for any problem.
    The user starts the query, it runs for sometime, then suddenly database crashes!
    Only way to work there after is to restart the database.
    Although I asked the user to not to run that query again but it is generated by some application which may generate similar query again!
    So, how I can prevent database from crashing again?
    Will creating a resource profile to allocate finite resource help? Problem is since database crashes so suddenly, I can't find any info from log files!
    Thanx

    The database instance crashes. We have to start the ORACLE.EXE again to up the database.
    Here is last few lines of the alert.log
    Fri Feb 05 11:14:59 2010
    Setting recovery target incarnation to 1
    Fri Feb 05 11:14:59 2010
    Successful mount of redo thread 1, with mount id 1911309359
    Fri Feb 05 11:14:59 2010
    Database mounted in Exclusive Mode
    Completed: alter database mount exclusive
    Fri Feb 05 11:14:59 2010
    alter database open
    Fri Feb 05 11:15:00 2010
    Beginning crash recovery of 1 threads
    parallel recovery started with 7 processes
    Fri Feb 05 11:15:00 2010
    Started redo scan
    Fri Feb 05 11:15:00 2010
    Completed redo scan
    3886 redo blocks read, 276 data blocks need recovery
    Fri Feb 05 11:15:00 2010
    Started redo application at
    Thread 1: logseq 179837, block 3
    Fri Feb 05 11:15:00 2010
    Recovery of Online Redo Log: Thread 1 Group 6 Seq 179837 Reading mem 0
      Mem# 0 errs 0: F:\DB LOG FILES\ORADATA\REDO06.LOG
      Mem# 1 errs 0: F:\DB LOG FILES MULTIPLEXED\ORADATA\REDO06.LOG
    Fri Feb 05 11:15:00 2010
    Completed redo application
    Fri Feb 05 11:15:00 2010
    Completed crash recovery at
    Thread 1: logseq 179837, block 3889, scn 10584777673
    276 data blocks read, 276 data blocks written, 3886 redo blocks read
    Fri Feb 05 11:15:01 2010
    LGWR: STARTING ARCH PROCESSES
    ARC0 started with pid=21, OS id=5752
    Fri Feb 05 11:15:01 2010
    ARC0: Archival started
    ARC1: Archival started
    ARC1 started with pid=22, OS id=4548
    Fri Feb 05 11:15:02 2010
    LGWR: STARTING ARCH PROCESSES COMPLETE
    Thread 1 advanced to log sequence 179838
    Thread 1 opened at log sequence 179838
      Current log# 7 seq# 179838 mem# 0: F:\DB LOG FILES\ORADATA\REDO07.LOG
      Current log# 7 seq# 179838 mem# 1: F:\DB LOG FILES MULTIPLEXED\ORADATA\REDO07.LOG
    Successful open of redo thread 1
    Fri Feb 05 11:15:02 2010
    ARC1: STARTING ARCH PROCESSES
    Fri Feb 05 11:15:02 2010
    ARC0: Becoming the 'no FAL' ARCH
    ARC0: Becoming the 'no SRL' ARCH
    Fri Feb 05 11:15:02 2010
    SMON: enabling cache recovery
    Fri Feb 05 11:15:02 2010
    ARC2: Archival started
    ARC1: STARTING ARCH PROCESSES COMPLETE
    ARC2 started with pid=23, OS id=6120
    Fri Feb 05 11:15:02 2010
    Successfully onlined Undo Tablespace 1.
    Fri Feb 05 11:15:02 2010
    SMON: enabling tx recovery
    Fri Feb 05 11:15:02 2010
    Database Characterset is WE8MSWIN1252
    replication_dependency_tracking turned off (no async multimaster replication found)
    Starting background process QMNC
    QMNC started with pid=25, OS id=5312
    Fri Feb 05 11:15:03 2010
    Completed: alter database open
    Fri Feb 05 11:15:03 2010
    ARC1: Becoming the heartbeat ARCH
    Fri Feb 05 11:16:01 2010
    Shutting down archive processes
    Fri Feb 05 11:16:06 2010
    ARCH shutting down
    ARC2: Archival stopped

  • Working with a complex query and trying to get rid of duplicates

    I'm working with the following complex query, and I need to
    select vin, number, year, make, model, and state from
    2007 vehicles in certain models, vin types
    2006 vehicles in certain models, vin types
    Is there a more efficient way to write this than how I've been writing it?:
    select distinct vehicle.vin VIN, unit.STATION_ID STID, unit.EMBEDDED_AREA_CODE||unit.EMBEDDED_PREFIX||lpad(unit.EMBEDDED_RON,4,0)
    MIN, unit.AUTHENTICATION_ID AUTHCODE, vehicle.user_veh_desc, veh_model.VEH_MODEL_DESC MODEL, veh_model.VEH_MANUF_YEAR YEAR, acct_veh.STATE STATE
    from vehicle
    inner join veh_unit on vehicle.vehicle_sak=veh_unit.vehicle_sak
    inner join unit on veh_unit.unit_sak=unit.unit_sak
    inner join vdu_profile on vdu_profile.vehicle_sak=vehicle.vehicle_sak
    inner join vdu_profile_program on vdu_profile_program.VDU_PROFILE_SAK=vdu_profile.VDU_PROFILE_SAK
    inner join veh_model on vehicle.VEH_MODEL = veh_model.VEH_MODEL
    inner join acct_veh on acct_veh.VEHICLE_SAK = vehicle.VEHICLE_SAK
    and vehicle.user_veh_desc like ('%2007%')
    AND unit.unit_gen_id >= 36
    AND vdu_profile_program.VDU_PROGRAM_SAK = 3
    and vdu_profile_program.PREFERENCE_VALUE = 'Y'
    and acct_veh.STATE in ('MN','ND','IA')
    AND (veh_model.VEH_MODEL_DESC like ('%Vehicle2%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle3%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle5%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle6%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle7%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle8%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle9%'))
    and ACCT_VEH.ACCT_VEH_STATUS_ID = 'A'
    and (vehicle.vin like ('_______3_________')
    or vehicle.vin like ('_______W_________')
    or vehicle.vin like ('_______K_________')
    or vehicle.vin like ('_______0_________'))
    UNION
    select distinct vehicle.vin VIN, unit.STATION_ID STID, unit.EMBEDDED_AREA_CODE||unit.EMBEDDED_PREFIX||lpad(unit.EMBEDDED_RON,4,0)
    MIN, unit.AUTHENTICATION_ID AUTHCODE, vehicle.user_veh_desc, veh_model.VEH_MODEL_DESC MODEL, veh_model.VEH_MANUF_YEAR YEAR, acct_veh.STATE STATE
    from vehicle
    inner join veh_unit on vehicle.vehicle_sak=veh_unit.vehicle_sak
    inner join unit on veh_unit.unit_sak=unit.unit_sak
    inner join vdu_profile on vdu_profile.vehicle_sak=vehicle.vehicle_sak
    inner join vdu_profile_program on vdu_profile_program.VDU_PROFILE_SAK=vdu_profile.VDU_PROFILE_SAK
    inner join veh_model on vehicle.VEH_MODEL = veh_model.VEH_MODEL
    inner join acct_veh on acct_veh.VEHICLE_SAK = vehicle.VEHICLE_SAK
    and vehicle.user_veh_desc like ('%2006%')
    AND unit.unit_gen_id >= 36
    AND vdu_profile_program.VDU_PROGRAM_SAK = 3
    and vdu_profile_program.PREFERENCE_VALUE = 'Y'
    and acct_veh.STATE in ('MN','ND','IA')
    AND (veh_model.VEH_MODEL_DESC like ('%Vehicle1%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle2%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle3%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle4%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle5%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle6%')
    OR veh_model.VEH_MODEL_DESC like ('%Vehicle7%'))
    and ACCT_VEH.ACCT_VEH_STATUS_ID = 'A'
    and (vehicle.vin like ('_______Z_________')
    or vehicle.vin like ('_______K_________'))

    I am not sure how many rows you have in the tables but I am assuming that there would be performance benefits in performing the query only once. You can combine similar coding and use an OR condition for the parts that are different. I left the 'K' vin comparison in both years for readability.
    I was not able to fully test my code but I believe that it will work as is. I hope it helps. If you are happier with the UNION you may want to investigate the WITH clause as you can query a subset of data twice, rather than the full data set.
    -- Common code 
    SELECT DISTINCT
       vehicle.vin,
       unit.station_id stid,
       unit.embedded_area_code || unit.embedded_prefix || LPAD (unit.embedded_ron, 4, 0) MIN,
       unit.authentication_id authcode,
       vehicle.user_veh_desc,
       veh_model.veh_model_desc model,
       veh_model.veh_manuf_year YEAR,
       acct_veh.state
    FROM vehicle
    INNER JOIN veh_unit           
       ON vehicle.vehicle_sak = veh_unit.vehicle_sak
    INNER JOIN unit               
       ON veh_unit.unit_sak = unit.unit_sak
    INNER JOIN vdu_profile        
       ON vdu_profile.vehicle_sak = vehicle.vehicle_sak
    INNER JOIN vdu_profile_program
       ON vdu_profile_program.vdu_profile_sak = vdu_profile.vdu_profile_sak
    INNER JOIN veh_model          
       ON vehicle.veh_model = veh_model.veh_model
    INNER JOIN acct_veh           
       ON acct_veh.vehicle_sak = vehicle.vehicle_sak     
    AND unit.unit_gen_id >= 36
    AND vdu_profile_program.vdu_program_sak = 3
    AND vdu_profile_program.preference_value = 'Y'
    AND acct_veh.state IN ('MN', 'ND', 'IA')
    AND acct_veh.acct_veh_status_id = 'A'
    AND
    -- Annual code
          (   -- 2006 conditions 
          AND vehicle.user_veh_desc LIKE ('%2007%')
          AND regexp_like(veh_model.veh_model_desc, 'Vehicle[2356789]')
          AND regexp_like(vehicle.vin, '_{7}[3WK0]_{9}')           
       OR
          (   -- 2007 conditions 
          AND vehicle.user_veh_desc LIKE ('%2006%')
          AND regexp_like(veh_model.veh_model_desc, 'Vehicle[1234567]')
          AND regexp_like(vehicle.vin, '_{7}[ZK]_{9}')
       ).

  • Working with multiple results of a complex query

    Hi all!
    As I "advance" in learning PL/SQL with oracle, I now get stuck in handling multiple results of a complex query. As far as I know, I cannot use a cursor here, as there is no table where the cursor could point to.
    Here is the concept of what I want to do (pseudocode):
    foreach result in SELECT * FROM table_1, table_n WHERE key_1 = foreign_key_in_n;
        -- do someting with the resultHere is my attemt, that freezes the browser gui and throws an internal database error:
    declare
        type t_stock is record(
                baggage_id  baggage.baggage_id%type,
                section_id  sections.section_id%type,
                shelf_id    shelves.shelf_id%type
        v_stock t_stock;
        rcnt number(2);
    begin
    dbms_output.put_line(TO_CHAR(rcnt));
    loop
         SELECT COUNT(*) INTO rcnt FROM (
                   SELECT baggage.baggage_id, sections.section_id, shelves.shelf_id
                   FROM baggage, sections, shelves
                   WHERE baggage.baggage_id = sections.contained_baggage_id
                        AND shelves.is_connex_to_section_id = sections.section_id);
         IF rcnt <= 0 THEN
              exit;
         END IF;
         SELECT baggage.baggage_id, sections.section_id, shelves.shelf_id INTO v_stock
         FROM baggage, sections, shelves
         WHERE baggage.baggage_id = sections.contained_baggage_id
              AND shelves.is_connex_to_section_id = sections.section_id
              AND ROWNUM < 2;
         UPDATE sections SET contained_baggage_id = NULL WHERE section_id = v_stock.baggage_id;
         commit; -- do I need that?
    end loop;
    END;
    /So, is there a way to traverse a list of results from a complex query? Maybe without creating a temporary table (or is that the better way?).
    regards, Alex
    I reformatted the code
    pktm

    Ok, here are the details:
    The tables are used to model kind of a transport system. There are terminals connected with sections that may contain 1 piece of baggage. The baggage is moved by a procedure through a transport system. After each of these "moving steps", I check if the baggage is in front of the shelf it should be in.
    [To be honest, the give statement doesn't contain the info, in which shelf the baggage wil bee inserted. That was spared out because of the lack of a working piece of code :)]
    But: if we consider the fact, that a baggage is in front of such a shelf in the way, that it should be put in this shelf, then all this makes some sense.
    - move baggae through a transport system
    - see if you can put baggage into a shelf
    In order to "put baggage in a shelf", I need to remove it from the transport section. As the transport system is not normalized, I need to update the section where the baggage was in.
    Uhm... yes it's a task that doesn't make too much sense. It seems to be some kind of general spirit in university homework :)
    But: the FOR r IN (Statement) lloks good. I'll use that.
    And, the ROWNUM < 2 is used to limit the size of the result to 1, there is no need to have a specific ordering. It's just because - afaik - oracle doesn't have a limit clause. I would appreciate your help if you know a better way to do limit resultsets.
    best regards, Alex

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

  • Query Help-2

    Query Help:
    http://forum.java.sun.com/thread.jsp?forum=45&thread=471180&tstart=15&trange=15
    It seems I have confused enough people with my improper presentation of query. Sorry guys. I will restate my question with different table names.
    The above was my previous posting, which was not clear..so Iam restating my problem as follows....
    I have the following tables
    Customer(custID, Name, Address)
    Order(custID, OrderID, orderDate)
    CreditCard(custID, creditCard#, creditCardType)
    Now if I have 3 records in Order with custID 100 and 2 records in CreditCard as
    Order:
    100,A001,11/22/03
    100,A002,11/24/03
    100,A003,12/02/03
    CreditCard:
    100,42323232..., VISA
    100,5234234...., MASTER
    Now how can I get
    custID, Name, Address, OrderID, orderDate, creditCard#, creditCarType
    data in minimum no. of records....
    I think I have made my query clear..
    now please help me guys...
    thanks so much for your help.

    You are right.
    But frankly the actual tables on my database are not customer,orders and creditcards..but I just tried to reproduce the problem with these tables, please ignore that user needs a refund etc situtaion. If the tables were actually order,creditcards etc..it would have been a problem to be considered.
    Can you please help me with the query
    if I have m rows in Order and n rows in CreditCard. I will get m*n records, I looking for max(m,n).
    With the following fields in my query result,
    custID, Name, Address, OrderID, orderDate, creditCard#, creditCarType
    from Customer, Order, CreditCard tables
    Thanks so much for your htlp

  • 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

  • SQL Query Help - Is this possible or impossible????

    Hi guys,
    I need help with an SQL query that I'm trying to develop. It's very easy to explain but when trying to implement it, I'm struggling to achieve the results that I want.....
    For example,
    I have 2 tables
    The first table is:
    1) COMPANY create table company (manufacturer varchar2(25),
                                                          date_established date,
                                                          location varchar2(25) );My sample test date is:
    insert into company values ('Ford', 1902, 'USA');
    insert into company values ('BMW', 1910, 'Germany');
    insert into company values ('Tata', 1922, 'India');The second table is:
    2) MODELS create table models (manufacturer varchar(25),
                                                 model varchar2(25),
                                                 price number(10),
                                                 year date,
                                                 current_production_status varchar2(1) ) ;My sample test data is:
    insert into models values ('Ford', 'Mondeo', 10000, 2010, 0);
    insert into models values ('Ford', 'Galaxy', 12000,   2008, 0);
    insert into models values ('Ford', 'Escort', 10000, 1992, 1);
    insert into models values ('BMW', '318', 17500, 2010, 0);
    insert into models values ('BMW', '535d', 32000,   2006, 0);
    insert into models values ('BMW', 'Z4', 10000, 1992, 0);
    insert into models values ('Tata', 'Safari', 4000, 1999, 0);
    insert into models values ('Tata', 'Sumo', 5500,   1996, 1);
    insert into models values ('Tata', 'Maruti', 3500, 1998, 0);And this is my query:
    SELECT
            com.manufacturer,
            com.date_established,
            com.location,
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.model),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.price),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.year),
            mod.current_production_status
    FROM
           company com,
           models mod
    WHERE
          mod.manufacturer = com.manufacturer
          and com.manufacturer IN ('Ford', 'BMW', 'Tata')
          and mod.current_production_status IN (1,0)
    ORDER BY
            mod.current_production_status DESCWhat I want the query to output is this:
    com.manufacturer        com.date_established          com.location          mod.model          mod.price             mod.year     mod.current_production_status
    Ford               1902                    USA               Escort               10000               1992          1
    BMW               1910                    Germany               -               -               -          0
    Tata               1922                    India               Sumo               5500               1998          1If current_production_status is 1 it means this particular model has been discontinued
    If current_production_status is 0 it means the manufacturer does not have any discontinued models and all are in procuction.
    The rule is only one record per manufacturer is allowed to have a current_production_status of 1 (so only one model from the selection the manufactuer offers is allowed to be discontinued).
    So the query should output the one row where current_production_status is 1 for each manufacturer.
    If for a given manufacturer there are no discontinued models and all have a current_production_status of 0 then ouput a SINGLE row that only includes the data from the COMPANY table (as above). The rest of the columns from the MODELS table should be populated with a '-' (hyphen).
    My query as it is above will output all the records where current status is 1 or 0 like this
    com.manufacturer        com.date_established          com.location          mod.model          mod.price          mod.year     mod.current_production_status
    Ford               1902                    USA               Escort               10000               1992          1
    Tata               1922                    India               Sumo               5500               1998          1
    Ford               1902                    USA               -               -               -          0                    
    Ford               1902                    USA               -               -               -          0
    BMW               1910                    Germany               -               -               -          0
    BMW               1910                    Germany               -               -               -          0
    BMW               1910                    Germany               -               -               -          0
    Tata               1922                    India               -               -               -          0
    Tata               1922                    India               -               -               -          0However this is not what I want.
    Any ideas how I can achieve the result I need?
    Thanks!
    P.S. Database version is '10.2.0.1.0'

    Hi Vishnu,
    Karthiks query helped...
    But this is the problem I am facing...
    SELECT
            com.manufacturer,
            com.date_established,
            com.location,
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.model),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.price),
            DECODE(nvl(mod.current_production_status, '0'), '0', '-', mod.year),
            mod.current_production_status
    FROM
           company com,
           models mod
    WHERE
          mod.manufacturer = com.manufacturer
          and com.manufacturer = 'Ford'
          and mod.current_production_status IN (1,0)
    ORDER BY
            mod.current_production_status DESCThe value of:
    and com.manufacturer = 'Ford'will be dependent on front end user input....
    When I run the query above I get all the rows where current_production_status is either 1 or 0.
    I only require the rows where current_production_status is 1.
    So if I amend it to look like this:
         and mod.current_production_status = 1This works....
    BUT if a user now passes in more than one manufacturer EG:
    and com.manufacturer IN ('Ford', 'BMW')The query will only return the one row for Ford where current_production_status is 1. However because BMW has no models where current_production_status is 1 (all 3 are 0), I still want this to be output - as one row....
    So like this:
    com.manufacturer        com.date_established          com.location          mod.model          mod.price             mod.year     mod.current_production_status
    Ford               1902                    USA               Escort               10000               1992          1
    BMW               1910                    Germany               -               -               -          0So (hopefully you understand), I want both cases to be catered for.....whether a user enters one manufacturer or more than one...
    Thanks you so much!
    This is really driving me insane :-(

Maybe you are looking for

  • Triggering IDoc LOIPRO01 for process orders.

    Hi, I have to create an IDOC LOIPRO01 and send to third party, whenever the save of the process order using COR1 and COR2 tcodes based on some conditions like plant US01, Order type ZC01 and released status Should I use the user exit EXIT_SAPLCOBT_00

  • Safari can't open, always crashes

    Just completed a java update from system update. Now Safari won't open. Searched through crash log and didn't see an error. Don't know what else to look for among the long list of words. Process: Safari [3499] Path: /Applications/Safari.app/Contents/

  • How to get page URL in a dynamic page in 10.1.4?

    Does anyone know how to get the page URL in a Dynamic Page in 10.1.4 without using javascript. I know that you can use a PL/SQL portlet and the portlet_record, but this is specifically for a Dynamic Page. Regards Jenny

  • Populating field with EXIT_SAPLEINM_002

    Hi, I have a requirement where i have to populate the Vendor Name field when PARVW = 'LF'(in ME22N-Create PO Transaction). Enhancement name:-MM06E001 INCLUDE           ZXM06U02 In Include LEINMF11,this is where i hv to make the changes:- int_edidd-se

  • ALV LIST - Amounts alignment

    Hi Experts, I worked on a development for showing G/L Balance sheet details. Screen shot as show below. We want to display the amounts of 'BALANCE SHEET TALLY' in proper format. The corresponding amounts should come under the respective Header. Like