Query with two where conditions

HI
SELECT ENAME FROM EMP WHERE
SAL > 1000 AND JOB='CLERK';
How to implement in CMP(Entity bean)
thank u

at this point mapping to do this king of query would be on the container specific file. I will tellyou how this is done on a Orion App server. I bet that others are close to the same.
first you make a finder method in your bean for the enploy name:
Collection findBigClerk();
Orion generates a file from the ejb-jar.xml file called orion-ejb-jar.xml. this is where the O/R mapping is changed for the beans.
each method in a bean has short definition
<finder-method query="EMP.SAL>1000 and EMP.JOB='CLERK'">
Assuming that the CMP is mapped to the EMP table when you call findbigClerk it will add the above query to as a WHERE clause.
Then get the name from the interface.
Again, this is how I would do this on an Orion App server. Others will be simular until O/R mapping is moved from server-specific to the ejb-jar.xml file
hope this helps a little

Similar Messages

  • Dynamic select query with dynamic where condition

    Hi all,
    I want to use the dynamic select query with dynamic where condition. For that I used the below code but I am getting dump when using this code.
    Please advice, if there is any other way to achieve this requirement.
    Thanks,
    Sanket Sethi
    Code***************
    PARAMETERS: p_tabnam      TYPE tabname,
                p_selfl1      TYPE edpline,
                p_value       TYPE edpline,
                p_where1      TYPE edpline .
    DATA: lt_where    TYPE TABLE OF edpline,
          lt_sel_list TYPE TABLE OF edpline,
          l_wa_name   TYPE string,
          ls_where    TYPE edpline,
          l_having    TYPE string,
          dref        TYPE REF TO data,
          itab_type   TYPE REF TO cl_abap_tabledescr,
          struct_type TYPE REF TO cl_abap_structdescr,
          elem_type   TYPE REF TO cl_abap_elemdescr,
          comp_tab    TYPE cl_abap_structdescr=>component_table,
          comp_fld    TYPE cl_abap_structdescr=>component.
    TYPES: f_count TYPE i.
    FIELD-SYMBOLS : <lt_outtab> TYPE ANY TABLE,
    *                <ls_outtab> TYPE ANY,
                    <l_fld> TYPE ANY.
    struct_type ?= cl_abap_typedescr=>describe_by_name( p_tabnam ).
    elem_type   ?= cl_abap_elemdescr=>describe_by_name( 'F_COUNT' ).
    comp_tab = struct_type->get_components( ).
    comp_fld-name = 'F_COUNT'.
    comp_fld-type = elem_type.
    APPEND comp_fld TO comp_tab.
    struct_type = cl_abap_structdescr=>create( comp_tab ).
    itab_type   = cl_abap_tabledescr=>create( struct_type ).
    l_wa_name = 'l_WA'.
    CREATE DATA dref TYPE HANDLE itab_type.
    ASSIGN dref->* TO <lt_outtab>.
    *CREATE DATA dref TYPE HANDLE struct_type.
    *ASSIGN dref->* TO <ls_outtab>.
    * Creation of the selection fields
    APPEND p_selfl1 TO lt_sel_list.
    APPEND 'COUNT(*) AS F_COUNT' TO lt_sel_list.
    ** Creation of the "where" clause
    *CONCATENATE p_selfl1 '= '' p_value ''.'
    *            INTO ls_where
    *            SEPARATED BY space.
    *APPEND ls_where TO lt_where.
    * Creation of the "where" clause
    APPEND p_where1 TO lt_where.
    * Creation of the "having" clause
    l_having = 'count(*) >= 1'.
    * THE dynamic select
    SELECT          (lt_sel_list)
           FROM     (p_tabnam)
           INTO CORRESPONDING FIELDS OF TABLE <lt_outtab>.
    *       WHERE    (lt_where).

    Hi Sanket,
    The above given logic of mine works for you, put the code in the If condition and try-
    just like below:
    IF NOT P_EBELN IS INITIAL.
    lt_where = '& = ''&'' '.
    REPLACE '&' WITH p_ebeln INTO lt_where.
    REPLACE '&' WITH field_value INTO lt_where.
    SELECT (lt_sel_list) INTO CORRESPONDING FIELDS OF TABLE <lt_outtab>
    FROM (p_tabnam)
    WHERE (lt_where).
    ENDIF.
    thanks\
    Mahesh

  • Single SQl Query with different where conditions

    Experts,
    I have a requirement to design a report. Here are the details
    I have Report table layout
    Profit center Gross sales (This Year) Gross Sales (Last Year) % change Year of Year
    The Report has a selection of entering the Start Date.
    I have a single table in oracle which has profit center and Gross Sales Values on daily basis.
    I want to write a single sql query to calculate both Gross Sales current year and Gross Sales Last Year. I can calculate Gross Sales Current Year by putting the where condition for start date = Current Year Date which i pass through report. I want to calculate the Gross Sales Last Year in the Same query by putting the different where condition i.e start date = Last Year date based on the date input.
    I dont know how to put two where conditions in single query for two different columns.
    Any help will be appreciated.
    Thanks in advance
    Regards
    Santosh

    instead of changing your where clause couldn't you just determine the yearly totals from your table and then use the lag statement to get last years total?
    something like this?
    I just made up 10,000 days worth of sales and called it fake table it is supposed to represent a variant of the table you were describing as your base table.
    with fake_table as
    ( select trunc(sysdate + level) the_day,
    level daily_gross_sales
    from dual
    connect by level < 10001
    select yr, year_gross_sale, lag(year_gross_sale) over (order by yr) prev_year_gross_sale,
    (year_gross_sale - lag(year_gross_sale) over (order by yr))/year_gross_sale * 100 percent_change
    from
    (select distinct yr, year_gross_sale from
    select the_day,
    daily_gross_sales,
    extract(year from the_day) yr,
    extract(year from add_months(the_day,12)) next_yr,
    sum(daily_gross_sales) over (partition by extract(year from the_day)) year_gross_sale
    from fake_table
    order by yr
    )

  • Select query with optional where condition

    Hi,
    Can Anybody help me out in the following problem?
    I have the following query in a procedure.
    SELECT replace(shipper_name,'\',' ') as shipper,
    sum(teus / cntSailings) as teus
    FROM VW_CONTRIBUTION,
    VW_TOTAL_SAILINGS
    WHERE VW_CONTRIBUTION.dir = VW_TOTAL_SAILINGS.DIR
    AND VW_CONTRIBUTION.line = VW_TOTAL_SAILINGS.LINE
    AND VW_CONTRIBUTION.accounting_month = VW_TOTAL_SAILINGS.ACCOUNTING_MONTH
    AND VW_CONTRIBUTION.accounting_year = VW_TOTAL_SAILINGS.ACCOUNTING_YEAR
    AND VW_CONTRIBUTION.Principal = arg_principal
    AND VW_CONTRIBUTION.Dir = arg_direction
    AND VW_CONTRIBUTION.line in ( arg_service )
    AND VW_CONTRIBUTION.POL_country = arg_pol
    AND VW_CONTRIBUTION.POd_country = arg_pod
    AND VW_CONTRIBUTION.salesOffice = arg_SalesOffice
    AND VW_CONTRIBUTION.salesregion = arg_SalesRegion
    AND VW_CONTRIBUTION.cargo_type = arg_txtCargoType
    AND VW_CONTRIBUTION.eqgroup = arg_ContType
    AND VW_CONTRIBUTION.eq_size = arg_txtSize
    AND VW_CONTRIBUTION.acct_date between arg_from_date and arg_end_date
    GROUP BY shipper_name
    ORDER BY teus desc;
    Here some of the arguments are optional(Eg : VW_CONTRIBUTION.salesOffice, AND VW_CONTRIBUTION.eqgroup etc. ) and the values can be null. When they are null, I want them to be excluded from the where condition. Can anybody suggest me a solution for this?
    Thanks,
    Shalet.

    I guess i misunderstood your original question.
    The clause
    AND (VW_CONTRIBUTION.salesOffice = arg_SalesOffice OR VW_CONTRIBUTION.salesOffice IS NOT NULL)
    will cause the where clause to evaluate to FALSE anytime salesOffice IS NULL so the record will be excluded.
    I thought you were asking how to not compare the value if the field contained a NULL.
    Glad you found what you wanted.

  • How to write the select query with complex where condition

    Hi all,
    Can u help me in writing  following select query.
    select * from zu1cd_corr where time_stamp between firstday and lastday .
    In the above query time_stamp contains the date and time.
    where as firstday and lastday contains the dates.
    I need to compare the date in the time_stamp with the firstday and lastday.
    But time_stamp contains the time also and it is char of 14 characters length.

    Hi,
    If that is the case u can do as advait specified....
    if the firstday and secondday are select-options then declare two more variables having 14 character length and then concatenate '000000' to firstday variable and '240000' to last day variable and then write ur query.
    CLEAR : lv_firstday,
                 lv_lastday.
    concatenate firstday '000000' to lv_firstday.
    concatenate lastday '240000' to lv_lastday.
    ranges : r_Date for zu1cd_corr-time_stamp.
    r_date-sign = 'I'.
    r_date-option = 'BT'.
    r_Date-low = lv_firstday.
    r_Date-high = lv_lastday.
    append r_date.
    select * from zu1cd_corr  into table it_zu1cd_corr where time_stamp in  r_Date.
    I hope it helps.
    Regards,
    Nagaraj

  • Select three tables data with Same where condition

    Hi i want sum data in three tables with same where condition. how can i do this code very simple.
    SELECT SUM(SIGNA) FROM dbo.tblPLAG 
    WHERE   VERSION='ACTUAL' AND STATS='ST_Z010'
    AND FACILITY='FA_2003'
    AND  TD IN  ( SELECT TIMEID FROM Time   WHERE   ID BETWEEN 
     @YEAR+'.'+(SELECT RIGHT ('000'+ CAST (@PERIOD-6 AS varchar), 3)) 
     AND   
    @YEAR +'.'+(SELECT RIGHT ('000'+ CAST (@PERIOD AS varchar), 3)))
       

    Try following
    SELECT SUM(t1.SIGNA) + sum(t2.SIGNA) + sum(t3.SIGNA) and you query, it will add the SUMs of each table.. hopefully it will work

  • CAML Query with 10 AND conditions

    Hello,
    I need some help with a CAML query. This particular query needs to have 10 AND conditions. Quite frankly, with all the nesting it is driving me a little nuts:
    What I have is:
    <Query>
    <Where>
    <And>
    <And>
    <And>
    <And>
    <And>
    <And>
    <And>
    <And>
    <And>
    <Eq><FieldRef Name='Column1' LookupId='TRUE' /><Value Type='Text'>10341</Value></Eq>
    <Eq><FieldRef Name='Column2' LookupId='TRUE' /><Value Type='Text'>9539</Value></Eq>
    </And>
    <Eq><FieldRef Name='Column3' LookupId='TRUE' /><Value Type='Text'>183</Value></Eq>
    </And>
    <Eq><FieldRef Name='Column4' LookupId='TRUE' /><Value Type='Text'>35</Value></Eq>
    </And>
    <IsNull><FieldRef Name='Column5' /></IsNull>
    </And>
    <Eq><FieldRef Name='Column6' LookupId='TRUE' /><Value Type='Text'>4387</Value></Eq>
    </And>
    <Eq><FieldRef Name='Column7' LookupId='TRUE' /><Value Type='Text'>4204</Value></Eq>
    </And>
    <Eq><FieldRef Name='Column8' LookupId='TRUE' /><Value Type='Text'>36</Value></Eq>
    </And>
    <Eq><FieldRef Name='Column9' LookupId='TRUE' /><Value Type='Text'>213</Value></Eq>
    </And>
    <IsNull><FieldRef Name='Column10' /></IsNull>
    </And>
    </Where>
    </Query>
    I have added this into my ItemAdding Event Receiver as it will basically do a check for duplicate items based on the 10 columns. 
    If anyone can help guide me in this, it would be much appreciated. I have been using a CAML Query Builder to help.

    http://webcache.googleusercontent.com/search?q=cache:xji7jOxa5_EJ:aasai-sharepoint.blogspot.com/2013/02/caml-query-with-multiple-conditions.html+&cd=3&hl=en&ct=clnk&gl=in
    http://stackoverflow.com/questions/6203821/caml-query-with-nested-ands-and-ors-for-multiple-fields
    Since you are not allowed to put more than two conditions in one condition group (And | Or) you have to create an extra nested group (MSDN). The expression
    A AND B AND C looks like this:
    <And>
    A
    <And>
    B
    C
    </And>
    </And>
    Your SQL like sample translated to CAML (hopefully with matching XML tags ;) ):
    <Where>
    <And>
    <Or>
    <Eq>
    <FieldRef Name='FirstName' />
    <Value Type='Text'>John</Value>
    </Eq>
    <Or>
    <Eq>
    <FieldRef Name='LastName' />
    <Value Type='Text'>John</Value>
    </Eq>
    <Eq>
    <FieldRef Name='Profile' />
    <Value Type='Text'>John</Value>
    </Eq>
    </Or>
    </Or>
    <And>
    <Or>
    <Eq>
    <FieldRef Name='FirstName' />
    <Value Type='Text'>Doe</Value>
    </Eq>
    <Or>
    <Eq>
    <FieldRef Name='LastName' />
    <Value Type='Text'>Doe</Value>
    </Eq>
    <Eq>
    <FieldRef Name='Profile' />
    <Value Type='Text'>Doe</Value>
    </Eq>
    </Or>
    If this helped you resolve your issue, please mark it Answered

  • Issue with Dynamic WHERE condition in Cursor in FUNCTION.

    Hi All,
    I am facing an issue with cursor having dynamic WHERE condition in a function.
    Below is the FUNCTION:
    CREATE OR REPLACE FUNCTION EXCEPTION_MERGE(TABLE_NAME IN VARCHAR2, TAB_NAME IN VARCHAR2)
    RETURN VARCHAr2
    IS
    stmt_tabcols VARCHAR2(32767);
    v_columnname VARCHAR2(32767);
    CURSOR C1 IS
    SELECT 'A.'||A.COLUMN_NAME ||' = '|| 'B.'||B.COLUMN_NAME COLUMN_NAME
    FROM
    SELECT COLUMN_ID, COLUMN_NAME
    FROM USER_TAB_COLUMNS
    WHERE TABLE_NAME  = TABLE_NAME
    AND COLUMN_NAME NOT IN ('ERROR_TAB_ID','ERROR_LOAD_DATE')
    ) A,
    SELECT COLUMN_ID, COLUMN_NAME
    FROM USER_TAB_COLUMNS
    WHERE TABLE_NAME = TAB_NAME
    ) B
    WHERE A.COLUMN_ID = B.COLUMN_ID;
    BEGIN
    FOR TABCOL IN C1
    LOOP
        stmt_tabcols := stmt_tabcols ||TABCOL.COLUMN_NAME||',';
    END LOOP;
        stmt_tabcols := RTRIM(stmt_tabcols, ',');
        RETURN stmt_tabcols;
    END;
    SELECT EXCEPTION_MERGE('WC_W_TEST_FS','WC_W_TEST_FS_GBL') FROM DUAL;It throws, below error:
    ORA-06502 : PL/SQL : Numeric or value error : character string buffer too smallIf I REPLACE TABLE_NAME and TAB_NAME with hard coded values , it works fine. Can somebody look at the code and let me know the issue.
    Edited by: ace_friends22 on Sep 9, 2012 1:08 PM

    Etbin neatly demonstrating the value of posting code in a manner which makes it easy to read.
    It's obviously an naming/scoping issue. Faced with a join like this:
    where table_name = table_namethe engine looks for something called table_name in the current scope. It finds it, a column on USER_TAB_COLUMNS and applies it to both sides of the filter. It has no way of knowing that there is also a parameter called TABLE_NAME, because that is outside its current scope. Consequently the query will join every table in your schema regardless of what values you pass, and that's why you blow the buffer.
    Takw etbin's advice and name your parameter with a prefix:
    where table_name = p_table_nameThis isn't a column in USER_TAB_COLUMNS which will force the engine to look in the next scope up, which in your case is the function, where it will find your parameter and so generate a query for the passed values only.
    Cheers, APC
    Edited by: APC on Sep 9, 2012 8:03 AM

  • DocumentClient query with Int64 where clause is incorrect when converted and sent to Azure

    The code below constructs a query with a lambda expression involving an Int64. When the query is converted and sent to Azure, it is incorrect. I captured the request to Azure using Fiddler for the example below, and the body contained:
    {"query":"SELECT * FROM root WHERE (root.car.id = 1.01036229983142E+16) "}
    Notice the constant does not match that of the code. Is this a bug in Azure DocumentDB library? If so, where can I submit a bug?
    long carId = 10103622998314238;
    IQueryable<MyDocument> query = documentClient.CreateDocumentQuery<MyDocument>("<collectionLinkGoesHere>", new FeedOptions { MaxItemCount = 1 });
    query = query.Where((MyDocument d) => d.Car.Id == carId);
    await query.AsDocumentQuery().ExecuteNextAsync<T>();

    @kurifodo1, DocumentDB follows the JSON standard for numbers, which is http://en.wikipedia.org/wiki/IEEE_754 notation. So any long integer gets serialized to a double stored as IEE754, and will lose some precision. While this isn't the most intuitive behavior,
    it's important in order to be compliant with other tools and platforms that speak JSON.
    If you'd like to just perform equality queries, consider storing this as a string. If you'd like to perform range queries, consider breaking up the number into two parts (high and low), similar to the BigInteger structure in C#.
    Hope this helps.

  • Query with two spatial operators

    Hi,
    I need prepare query with sdo_any_interact and sdo_filter
    Following query doesn't work any ideas?
    SELECT ROWID, GEOMETRY, 'MVDEMO:L.MAJOR TOLL ROAD', null, 'null', -1, 'rule#0'
    FROM PARCELS P
    WHERE SDO_ANYINTERACT(P.GEOMETRY,
    (SELECT L.GEOMETRY
    FROM SHP_SIMPLYFIED L
    WHERE L.TASK = '4')) = 'TRUE'
    and MDSYS.SDO_FILTER(P.GEOMETRY
    , MDSYS.SDO_GEOMETRY(2003
    , 2180
    , NULL
    , MDSYS.SDO_ELEM_INFO_ARRAY(1, 1003, 3)
    , MDSYS.SDO_ORDINATE_ARRAY(482850, 236980, 510333, 248133))
    --, MDSYS.SDO_ORDINATE_ARRAY(:MVQBOXXL, :MVQBOXYL, :MVQBOXXH, :MVQBOXYH))
    , 'querytype=WINDOW') = 'TRUE'
    Kind regards,
    Tomek

    Hi Jack,
    Join - the same error:
    the error is
    ORA-00904: "MDSYS"."SDO_PQRY": invalid identifier
    00904. 00000 - "%s: invalid identifier"
    *Cause:
    *Action:
    Error at Line: 13 Column: 60
    TASK column - is not null, unique
    parcels are partitioned table (3 000 000 rows)
    i think this error is connected with partitoning
    in the first version i put any_interact into view with read only option
    select * from this view works fine but take a long time,
    next i build theme in MapBuider but preview return error (same), (MapBuilder buid query on view and add query_window filter to reduce number of objects)
    Thx,
    Tomek

  • Query with Top N Condition (Result Row)

    Hi,
    I made a query with an active top n condition. The query has 2 Keyfigures and 1 formula
    Gross-sales acutal | Gross-sales previous year | Previous Year %
    So that to result line is correct, I had to say "Calculate result as summation" for the keyfigures
    gross sales actual and gross sales previous year. That works.
    I have the problem with my formula. the formular for previous year % is defined as follows:
    gross sales actual %A gross sales previous year
    Example Top 3 Customer
                        gross sales actual          gross sales prev. year         prev. year %
    Cust 1          100                                   80                                       125 %
    Cust 2          90                                     45                                        200 %
    Cust 3           80                                    60                                        133 %
    Result          270                                   185                                       142.8 % ( 350 * 100 / 245 )
    The result of 142 % is the correct result without the condition top 3. with the top 3 condition
    the result should be 270 * 100 / 185 = 145.9 %
    Additional customer without top 3 condition
    Cust 4          50                                       40                                        125 %
    Cust 5          30                                        20                                        150 %
    It shows the correct result for each single line. The result in the result row is wrong. it is calculated
    without taking the active condition. the formular calculates
    with the total gross sales actual and the total of gross sales prev. year.
    is there any solution the achieve the correct % in the result row?
    thanks for your help.
    Pascal

    Pascal,this is a known behavior with conditions.When you apply condition it just hide the extra rows and it does not impact the result row.So your result row actually shows the value irrespective of the condition you apply.
    Now with the help of local functions like calculate result as summation you can show the correct sum after applying the condition but when you try to use that result in some calculation then it takes the original value thereby discarding the calculated value.
    Same is happening in your case as well.Its taking the original value i.e 350 and not the calculated sum after condition i.e 270.
    Hope this helps.
    Regards,
    AL

  • Crystal report based on BW query with two structures

    Hi,
    I use a BW query with 2 structures. In the rows there is a structure of restricted characteristic 0material. I used this characteristics several times in different rows to restrict these rows to specific products.
    Cars
    motorcycles
    Others
    In the columns I have a structure of key figures. Every key figure is restricted to a specific time intervall.
    So in BW the executed query looks like this:
                           Key figure 1         Key figure 2        Key figure 3
      Cars                   10                     30                         100
      motorcycles        20                   100                          30
      Others                30                    40                           39
    If I use the same query in Crystal then I have access to the 3 keyfigures and to one structure element.
    How can I ensure that the query is displayed in CR like in BW? I tried to work with crosstabs but I was not able to get the same display like in BW.
    Thanks for any help.
    BR, Andreas

    Try posting your question to the BW / SAP forum.

  • How to execute procedure with dynamic where condition.

    Hi All,
    I am facing a probelem
    Issue :
    I am having a parameter p_id in my procedure based on the value of this parameter i want to change the where condition.
    How to do so?
    Code:---------
    create or replace procedure p_1
    ( p_id in emp_dummy.empno%type)
    is
    parameter_1 varchar2(2000);
    v_sal number;
    begin
    if p_id = 1 then
    parameter_1 := 'where empno = 1';
    else
    parameter_1 := 'where 1=1';
    end if;
    select salary into v_sal from emp_dummy||' '||parameter_1;
    end;

    Dynamic SQL is not the best of ideas, but if you must...
    EXECUTE IMMEDIATE 'select salary from emp_dummy where empno=nvl(:x,empno)' into v_sal using p_id;Then if you pass in the p_id to the procedure it will select the salary for that employee and if null is passed in then it will select the salary for all employees. Now here's a problem because you are trying to return a single value and if you don't specify the employee then it will try and return multiple values from that select, so you probably want to do something like give the sum of the salaries...
    EXECUTE IMMEDIATE 'select sum(salary) from emp_dummy where empno=nvl(:x,empno)' into v_sal using p_id;

  • Query with two registers, when i use two taxcode

    Hi everybody, my question in this opportunity, it's about  this query:
    /*LIBRO DE COMPRAS CELULAR STRA S.A. DE C.V.*/
    SELECT T0.[TaxDate] Fecha,
           T0.[NumAtCard] 'DOCUMENTO',
           T1.[U_RegIva] 'NRC',
           T0.[CardCode] 'CODIGO DE PROVEEDOR',
           T1.[U_NIT] 'NIT',
           T0.[CardName] 'NOMBRE DE PROVEEDOR',
           SUM(CASE 
                  WHEN T2.[TaxCode] = 'IVAEXE' THEN T2.[LineTotal]
                  ELSE 0
               END) 'LOCALES EXENTAS',
           0.00 ImportacionesExentas,
            (SELECT sum(T12.[LineTotal]) FROM PCH1 T12 INNER JOIN OPCH T10 ON T12.[DOCENTRY] = T10.[DOCENTRY] WHERE T12.[AcctCode] != '11209' AND T12. [TaxCode]  = 'IVACCF' AND T12.[DOCENTRY] = T0.[DOCENTRY]  AND T10.[TaxDate] >= '[%0]' and T10.[TaxDate] <= '[%1]') 'LOCALES GRAVADAS',
            0.00 Importaciones,
            T0.[VatSumSy] 'CREDITO FISCAL',
                  T0.[DocTotal]+
    T0.[DocTotal] -(CASE
                         WHEN  T2.[ACCTCODE] = '11209'
                         THEN ((SELECT (T12.[LineTotal]*-1)
                         FOM PCH1 T12
              INNER JOIN OPCH T10 ON T12.[DOCENTRY] = T10.[DOCENTRY]
                    WHERE T12.[AcctCode] = '11209' AND
                    ---T12.[TaxCode]  = 'IVACCF' AND
                     (T12.[DOCENTRY] = T0.[DOCENTRY])  AND
                         T10.[TaxDate] >= '[%0]' and T10.[TaxDate] <= '[%1]'))
                           ELSE T0.[DOCTOTAL] END) 'TOTAL COMPRAS', --This statement, cause the error, or,  think so i
            (SELECT SUM(T13.[WTAMNT]) FROM PCH5 T13 WHERE (T13.[WTCode] = 'RET1' OR T13.[WTCode] = 'RET2') AND T13.[ABSENTRY] = T0.[DOCENTRY] )'RETENCION IVA',
           0.00 ComprasExcluidos
    FROM OPCH T0
       INNER JOIN OCRD T1 ON T0.[CardCode] = T1.[CardCode] INNER JOIN PCH1 T2 ON T0.[DocEntry] = T2.[DocEntry]
    WHERE T0.[TaxDate] >= '[%0]' and T0.[TaxDate] <= '[%1]' AND T1.[Country] = 'SV' AND T0.[Series] = 7 and
       t0.docnum not in (SELECT distinct T0.[DocNum] FROM [dbo].[OPCH] T0 INNER JOIN [dbo].[PCH1] T1 ON T0.DocEntry = T1.DocEntry
                                                                          inner join RPC1 T2 on t1.trgetEntry=t2.docentry INNER JOIN ORPC T3 ON T2.DocEntry = T3.DocEntry
                         WHERE T3.[TaxDate] >= '[%0]' and  T3.[TaxDate] <= '[%1]' and t3.series=9) AND
          T0.NumAtCard NOT LIKE '%F%' AND
          T0.NumAtCard NOT LIKE '%REDIGIT%'
    GROUP BY T0.[TaxDate],
             T0.[DocNum],
             T0.[CardName],
             T0.[CardCode],
             T1.[U_NIT],
             T0.[VatSumSy],
             T0.[DOCENTRY],
             T0.[DocDate],
             T0.[DOCTOTAL],
             T0.[NumAtCard],
             T1.[U_RegIva],
            T2.[AcctCode],
            T0.[DocTotal]
    the result shows two line with the information of one vendor invoice,
    example:
    numatcard     cardcode      tax exempt     local shopping   tax     total
    12345           0125             0.00             100         13      115
    12345           0125             2.00             100         13      115
    i think this be must to tax indicator, because in the document i use two diferent taxcode. i need help to avoid this error, if somebody know how resolved, me will great util

    Well Gordon,
    If you see in the statement, the register is in one line:
    (SELECT sum(T12.[LineTotal]) FROM PCH1 T12 INNER JOIN OPCH T10 ON T12.[DOCENTRY] = T10.[DOCENTRY] WHERE T12.[AcctCode] != '11209' AND T12. [TaxCode] = 'IVACCF' AND T12.[DOCENTRY] = T0.[DOCENTRY]  AND T10.[TaxDate] >= '[%0]' and T10.[TaxDate] <= '[%1]')
    to better expalin.
    i have this line  without tax, i only need a statement in the that be sum, the line of tax exempt + line without tax + tax total.
    if you see in the query, i've excluded the acctcode = '11209', really without this filter, only  i need select the doctotal to view the result. but if, i do a statement where only excluide the document line where appear this account, the quey returns a wrong

  • Hierarchy query with dynamic start condition

    Hi,
    I have a table that stores hierarchical items (foohierarchy) and another one storing users and such items (useritems). Unfortunately the latter one is not consistent and misses some entries. I would like to fix that using pure sql. Fixing here means that a user that possesses a certain child element should also have parents of that child. There are a couple of obstacles here though. First the hierarchy table does not explicitly state which elements are top level elements. I am trying to fix that by emulating a proper structure and named that fixedhierarchy. A select statement that returns all intended user/item relationships would be nice.
    Here some visualization and sample data, the sample data follows the pattern that each item uses its level as its suffix, but this shouldn't be exploited in the statement:
    asci art:
    -- A1 (peter,paul)
    --   \_ B2
    --   \_ C2
    --        \_D3 (thomas)
    --            \_X4
    -- E1
    --   \_F2
    -- G1
    --   \_H2 (heidi)sample data
    drop table foohierarchy;
    drop table useritems;
    create table foohierarchy (
    child_item varchar2(30),
    parent_item varchar2(30));
    insert into foohierarchy values ('B2','A1');
    insert into foohierarchy values ('C2','A1');
    insert into foohierarchy values ('D3','C2');
    insert into foohierarchy values ('X4','D3');
    insert into foohierarchy values ('F2','E1');
    insert into foohierarchy values ('H2','G1');
    create table useritems (
    username varchar2 (40),
    item varchar2(30)
    insert into useritems values ('peter','A1');
    insert into useritems values ('paul','A1');
    insert into useritems values ('thomas','D3');
    insert into useritems values ('heidi','H2');
    commit;my attempt at fixing the hierarchy table
    with fixedhierarchy as
    (select parent_item,child_item from foohierarchy
    union all
    select distinct null parent_item,parent_item child_item from foohierarchy where parent_item not in (select child_item from foohierarchy))
    select * from fixedhierarchy;What the select should return:
    'peter'|'A1'
    'paul'|'A1'
    'thomas'|'A1'
    'thomas'|'C2'
    'thomas'|'D3'
    'heidi'|'G1'
    'heidi'|'H2'

    Hi,
    Thanks for posting the CREATE TABLE and INSERT statments; that's very helpful! Don't forget to mention what version of Oracle you're using. That's especially important with hierachies; every version since Oracle 7 has had significant improvements in how to handle them.
    I'm a little comfused as to what you want. Are you trying to permanently change the tables? If so, show what the changed table(s) should look like when the job is finished. Post the output you would want to see from "SELECT * FROM useritems;" or "SELECT * FROM foohierarchy;", or, if you want to change both tables, from both.
    It looks like you have two separate problems:
    (1) Changing foohierarchy, so that every item appears once as a child_id. That means adding rows with NULL parent_item for all the roots ('A1', 'E1' and 'G1'). The query you posted seems directed toward this.
    (2) Denormalizing useritems, so that when a username is linked to an item, the username is linked to all that item's ancestors, too. The results you posted seem to be what you want useritems to look like after this is done.
    Here's how to do those things:
    <h4>(1) Changing foohierarchy</h4>
    The query you posted looks good. Do you see anything wrong with it? You can use that query (or something very close to it) in an INSERT or MERGE statement.
    If you just want to add some new rows to foohierarchy, then you don't need the UNION: just the second branch of it. If you're cvertain that none of those rows already exist in foohierarchy, then
    INSERT INTO foohierarchy (parent_item,      child_item)
         SELECT DISTINCT   NULL,          childitem
         FROM     foohierarchy
         WHERE     parent_item     NOT IN (
                             SELECT      child_item
                             FROM     foohierarchy
    ;If some of the roots might already be in foohierarchy correctly, then you'll want a something in the WHERE clause to make sure you don';t add a duplicate. A MERGE statment might do this better than INSERT.
    <h4>(2) Denormalizing useritems</h4>
    This adds new rows to useritems, to make it look like what you posted:
    ERGE INTO     useritems     dst
    USING (
         WITH     all_ancestors     AS
              SELECT     CONNECT_BY_ROOT child_item     AS descendant
              ,     parent_item               AS ancestor
              FROM     foohierarchy
              START WITH     child_item   IN     (
                                       SELECT     item
                                       FROM     useritems
              CONNECT BY     child_item   = PRIOR parent_item
         SELECT DISTINCT
              u.username
         ,     a.ancestor
         FROM     all_ancestors     a
         JOIN     useritems     u  ON     a.descendant     = u.item
          )                    src
    ON     (     src.username     = dst.username
         AND     src.ancestor     = dst.item
    WHEN NOT MATCHED THEN
         INSERT     (dst.username,     dst.item)
         VALUES     (src.username,     src.ancestor)
    ;After doing this, "SELECT * FROM useritems;" will produce this output:
    USERNAME   ITEM
    paul       A1
    peter      A1
    thomas     A1
    thomas     C2
    thomas     D3
    heidi      G1
    heidi      H2Here's how it works:
    Sub-query all_ancestors is a bottom-up CONNECT BY query, linking each node in useritems with all of its ancestors. CONNECT BY queries are often slow under the best circumstances; doing a join in a CONNECT BY query makes it even slower. It's more efficient to do the CONNECT BY query first, in a sub-query, and then join tht result set to other tables, as I did in src.

Maybe you are looking for