Confusion in Select query having a inner join on single table

Hi,
I was going through coding and came a accross a select query which has a inner join on a single table. I am getting confused while analysing this . Please someone can help me analysing this query.
select
        m~MATERIAL
        s~NUMERATOR s~DENOMINTR
        m~GROSS_WT  m~UNIT_OF_WT
      into table itab
      from ( table1as s
       inner join table1 as m
       on  m~MATERIAL = s~MATERIAL
      and m~MAT_UNIT = 'CS'
      and m~SOURSYSTEM = s~SOURSYSTEM )
      where s~MAT_UNIT = 'EA'
         and s~SOURSYSTEM = 'LD'
         and s~OBJVERS = 'A'
         and s~MATERIAL IN ( Select mat_sales
            from Table2  group by mat_sales ).
Thank you
Kusuma

I don't see any use of the INNER JOIN here.
But what's the meaning of the last selection clause?
s~MATERIAL IN ( Select mat_sales
            from Table2  group by mat_sales ).
Is that native SQL or something?
Pushpraj

Similar Messages

  • Can we implement the custom sql query in CR for joining the two tables

    Hi All,
    Is there anyway to implement the custom sql query in CR for joining the two tables?
    My requirement here is I need to write sql logics for joining the two tables...
    Thanks,
    Gana

    In the Database Expert, expand the Create New Connection folder and browse the subfolders to locate your data source.
    Log on to your data source if necessary.
    Under your data source, double-click the Add Command node.
    In the Add Command to Report dialog box, enter an appropriate query/command for the data source you have opened.
    For example:
    SELECT
        Customer.`Customer ID`,
        Customer.`Customer Name`,
        Customer.`Last Year's Sales`,
        Customer.`Region`,
        Customer.`Country`,
        Orders.`Order Amount`,
        Orders.`Customer ID`,
        Orders.`Order Date`
    FROM
        Customer Customer INNER JOIN Orders Orders ON
            Customer.`Customer ID` = Orders.`Customer ID`
    WHERE
        (Customer.`Country` = 'USA' OR
        Customer.`Country` = 'Canada') AND
        Customer.`Last Year's Sales` < 10000.
    ORDER BY
        Customer.`Country` ASC,
        Customer.`Region` ASC
    Note: The use of double or single quotes (and other SQL syntax) is determined by the database driver used by your report. You must, however, manually add the quotes and other elements of the syntax as you create the command.
    Optionally, you can create a parameter for your command by clicking Create and entering information in the Command Parameter dialog box.
    For more information about creating parameters, see To create a parameter for a command object.
    Click OK.
    You are returned to the Report Designer. In the Field Explorer, under Database Fields, a Command table appears listing the database fields you specified.
    Note:
    To construct the virtual table from your Command, the command must be executed once. If the command has parameters, you will be prompted to enter values for each one.
    By default, your command is called Command. You can change its alias by selecting it and pressing F2.

  • Inner join on Buffred table and not buffered table.

    Hi guys,
       Can you suggest me how can i write select query using inner join on buffered table and not buffered table. i written like this. is it right?
    SELECT a~vbeln                         
             a~vkorg   
             a~kunnr                         
             a~kunag                         
             a~wadat_ist 
             a~xblnr                         
             b~bukrs
       FROM likp AS a INNER JOIN tvko AS b
        ON avkorg = bvkorg BYPASSING BUFFER
      INTO TABLE itab_likp
      WHERE vbeln = s_vbeln.              
    Thanks.
    RAJ

    Hi Raj ,
    Please find below my Commentes :
    1. When you use "Bypassing buffer" clause in Select statement , the data what is there in the buffer of application sever is always ignored and Read is performed from the Physical database always. This Clause is advisable where you require realtime data (Not recommended generally in reporting)
    2. It is advisable that you should not use small table in the innerjoin with big table. In the query you have written there are 2 tables:- LIKP and TVKO outof which TVKO is a master table containing very few records than LIKP (Contains huge data for Delivery header).
    So my recommendation will be : -
    1. Eliminate the "Bypassing Buffer" clause from your Query
    2. Break the select query into 2 select queries breaking the join and with some ABAP logic populate the Internal table "itab_likp".
    This will be optimum way inwhich you can write the select query for your senarion. Also Ensure that indexes are being used for better selectivity.
    Hope this will help to you.
    Regards,
    Nikhil

  • How to create a DB Adapter with select query having inner query

    Hi All,
    I am trying to create a DB Adapter with select query. The query has some inner queries in it. It is just like this select a, b, c, (select d from e) d, (select e from e) e from tablename.
    The problem here is with the xsd generated for this query. Xsd is not getting generated properly for all the fields it is just getting generated till c element and when it encounters
    the inner query it is stopping the generation of xsd. So for the above query the xsd is something similar to the below
    <xs:complexType name="rewOutput">
    <xs:sequence>
    <xs:element name="a" type="xs:string" nillable="true"/>
    <xs:element name="b" type="xs:string" nillable="true"/>
    <xs:element name="c" type="xs:string" nillable="true"/>
    <xs:element name="select_d" type="xs:string" nillable="true"/>
    </xs:sequence>
    </xs:complexType>
    as shown above the xsd is just getting generated till the first inner query. What should be done to get the full fledged xsd. Should it be manually built ?? Please help me on this.
    Thanks In Advance.
    Edited by: 959766 on Nov 30, 2012 1:20 AM

    Hi,
    I don't think the parser will be able to understand your query properly... I would try building the xsd manually...
    Cheers,
    Vlad

  • Dynamic From statement in select query and/or outer join not working

    Dear Experts, I have a select query where the select columns are dynamic, the where condition is also dynamic. It is of the below format:
    Select (dynamic columns) INTO <wa>
    FROM a inner join b on af1 = bf1
    inner join c on af2 = cf2......
    WHERE (dynamic conditios)
    ORDER BY ( dynamic sort condition).
    Now I have to include some tables (dynamically depending on the user input) in the inner join statement which will give description for the selected fields. And these database tables may or may no be empty. So in this case, my select query will not return any data if these tables are empty. And I dont want that.
    I tried using outer join for the extra tables but it gave me a runtime error. I also tried forming the inner join statement dynamically but it was not supporting.
    Kindly give me pointers.
    Thanks

    Hey thanks for the reply, but the problem is not solved.
    I am already using  ( fileds, value) like table in my where condition and the select statement was working properly.
    the problem is that now I have to include some tables in the join statement which can be empty and so i want to use Outer join.
    But I am getting a runtime error as below:
    Error analysis
        An exception occurred that is explained in detail below.
        The exception, which is assigned to class 'CX_SY_DYNAMIC_OSQL_SYNTAX', was not
         caught in
        procedure "ZATSCSNG_RFC_READ_TABLE" "(FUNCTION)", nor was it propagated by a
         RAISING clause.
        Since the caller of the procedure could not have anticipated that the
        exception would occur, the current program is terminated.
        The reason for the exception is:
        The running ABAP program wanted to execute a SELECT statement whose
        WHERE condition was (partly) specified dynamically. The part that is
        specified in an internal table at runtime is compared to a field of the
        right table of an LEFT OUTER JOIN. Such comparisons are not supported by
         all database systems and are therefore not allowed.

  • Query related to inner join V/S all entries........

    Hi all,
    I have a dought ...related to join and all entries
    Which one will be the better as per performance prospective :
    1>For all entries
    or
    2> using inner join condition
    i am combining 2 tables ...
    but in my where clause is having 6-7 condition if i used inner join concept...
    Please let me know thanks for the help...in advance
    regards
    Amit

    Check Re: Multiple Table Join instead of Nested Selects? I wrote a program that compares the performance of a join against for all entries. The join won. But the best thing to do is for you test and compare both methods for your particular situation.
    In a select, the most important factor is the use of an index.
    Rob

  • Very Slow Query with CTE inner join

    I have 2 tables (heavily simplified here to show relevant columns):
    CREATE TABLE tblCharge
    (ChargeID int NOT NULL,
    ParentChargeID int NULL,
    ChargeName varchar(200) NULL)
    CREATE TABLE tblChargeShare
    (ChargeShareID int NOT NULL,
    ChargeID int NOT NULL,
    TotalAmount money NOT NULL,
    TaxAmount money NULL,
    DiscountAmount money NULL,
    CustomerID int NOT NULL,
    ChargeShareStatusID int NOT NULL)
    I have a very basic View to Join them:
    CREATE VIEW vwBASEChargeShareRelation as
    Select c.ChargeID, ParentChargeID, s.CustomerID, s.TotalAmount, isnull(s.TaxAmount, 0) as TaxAmount, isnull(s.DiscountAmount, 0) as DiscountAmount
    from tblCharge c inner join tblChargeShare s
    on c.ChargeID = s.ChargeID Where s.ChargeShareStatusID < 3
    GO
    I then have a view containing a CTE to get the children of the Parent Charge:
    ALTER VIEW [vwChargeShareSubCharges] AS
    WITH RCTE AS
    SELECT ParentChargeId, ChargeID, 1 AS Lvl, ISNULL(TotalAmount, 0) as TotalAmount, ISNULL(TaxAmount, 0) as TaxAmount,
    ISNULL(DiscountAmount, 0) as DiscountAmount, CustomerID, ChargeID as MasterChargeID
    FROM vwBASEChargeShareRelation Where ParentChargeID is NULL
    UNION ALL
    SELECT rh.ParentChargeID, rh.ChargeID, Lvl+1 AS Lvl, ISNULL(rh.TotalAmount, 0), ISNULL(rh.TaxAmount, 0), ISNULL(rh.DiscountAmount, 0) , rh.CustomerID
    , rc.MasterChargeID
    FROM vwBASEChargeShareRelation rh
    INNER JOIN RCTE rc ON rh.PArentChargeID = rc.ChargeID and rh.CustomerID = rc.CustomerID
    Select MasterChargeID as ChargeID, CustomerID, Sum(TotalAmount) as TotalCharged, Sum(TaxAmount) as TotalTax, Sum(DiscountAmount) as TotalDiscount
    from RCTE
    Group by MasterChargeID, CustomerID
    GO
    So far so good, I can query this view and get the total cost for a line item including all children.
    The problem occurs when I join this table. The query:
    Select t.* from vwChargeShareSubCharges t
    inner join
    tblChargeShare s
    on t.CustomerID = s.CustomerID
    and t.MasterChargeID = s.ChargeID
    Where s.ChargeID = 1291094
    Takes around 30 ms to return a result (tblCharge and Charge Share have around 3.5 million records).
    But the query:
    Select t.* from vwChargeShareSubCharges t
    inner join
    tblChargeShare s
    on t.CustomerID = s.CustomerID
    and t.MasterChargeID = s.ChargeID
    Where InvoiceID = 1045854
    Takes around 2 minutes to return a result - even though the only charge with that InvoiceID is the same charge as the one used in the previous query.
    The same thing occurs if I do the join in the same query that the CTE is defined in.
    I ran the execution plan for each query. The first (fast) query looks like this:
    The second(slow) query looks like this:
    I am at a loss, and my skills at decoding execution plans to resolve this are lacking.
    I have separate indexes on tblCharge.ChargeID, tblCharge.ParentChargeID, tblChargeShare.ChargeID, tblChargeShare.InvoiceID, tblChargeShare.ChargeShareStatusID
    Any ideas? Tested on SQL 2008R2 and SQL 2012

    >> The database is linked [sic] to an established app and the column and table names can't be changed. <<
    Link? That is a term from pointer chains and network databases, not SQL. I will guess that means the app came back in the old pre-RDBMS days and you are screwed. 
    >> I am not too worried about the money field [sic], this is used for money and money based calculations so the precision and rounding are acceptable at this level. <<
    Field is a COBOL concept; columns are totally different. MONEY is how Sybase mimics the PICTURE clause that puts currency signs, commas, period, etc in a COBOL money field. 
    Using more than one operation (multiplication or division) on money columns will produce severe rounding errors. A simple way to visualize money arithmetic is to place a ROUND() function calls after 
    every operation. For example,
    Amount = (Portion / total_amt) * gross_amt
    can be rewritten using money arithmetic as:
    Amount = ROUND(ROUND(Portion/total_amt, 4) * 
    gross_amt, 4)
    Rounding to four decimal places might not seem an 
    issue, until the numbers you are using are greater 
    than 10,000. 
    BEGIN
    DECLARE @gross_amt MONEY,
     @total_amt MONEY,
     @my_part MONEY,
     @money_result MONEY,
     @float_result FLOAT,
     @all_floats FLOAT;
     SET @gross_amt = 55294.72;
     SET @total_amt = 7328.75;
     SET @my_part = 1793.33;
     SET @money_result = (@my_part / @total_amt) * 
    @gross_amt;
     SET @float_result = (@my_part / @total_amt) * 
    @gross_amt;
     SET @Retult3 = (CAST(@my_part AS FLOAT)
     / CAST( @total_amt AS FLOAT))
     * CAST(FLOAT, @gross_amt AS FLOAT);
     SELECT @money_result, @float_result, @all_floats;
    END;
    @money_result = 13525.09 -- incorrect
    @float_result = 13525.0885 -- incorrect
    @all_floats = 13530.5038673171 -- correct, with a -
    5.42 error 
    >> The keys are ChargeID(int, identity) and ChargeShareID(int, identity). <<
    Sorry, but IDENTITY is not relational and cannot be a key by definition. But it sure works just like a record number in your old COBOL file system. 
    >> .. these need to be int so that they are assigned by the database and unique. <<
    No, the data type of a key is not determined by physical storage, but by logical design. IDENTITY is the number of a parking space in a garage; a VIN is how you identify the automobile. 
    >> What would you recommend I use as keys? <<
    I do not know. I have no specs and without that, I cannot pull a Kabbalah number from the hardware. Your magic numbers can identify Squids, Automobile or Lady Gaga! I would ask the accounting department how they identify a charge. 
    >> Charge_Share_Status_ID links [sic] to another table which contains the name, formatting [sic] and other information [sic] or a charge share's status, so it is both an Id and a status. <<
    More pointer chains! Formatting? Unh? In RDBMS, we use a tiered architecture. That means display formatting is in a presentation layer. A properly created table has cohesion – it does one and only one data element. A status is a state of being that applies
    to an entity over a period time (think employment, marriage, etc. status if that is too abstract). 
    An identifier is based on the Law of Identity from formal logic “To be is to be something in particular” or “A is A” informally. There is no entity here! The Charge_Share_Status table should have the encoded values for a status and perhaps a description if
    they are unclear. If the list of values is clear, short and static, then use a CHECK() constraint. 
    On a scale from 1 to 10, what color is your favorite letter of the alphabet? Yes, this is literally that silly and wrong. 
    >> I understand what a CTE is; is there a better way to sum all children for a parent hierarchy? <<
    There are many ways to represent a tree or hierarchy in SQL.  This is called an adjacency list model and it looks like this:
    CREATE TABLE OrgChart 
    (emp_name CHAR(10) NOT NULL PRIMARY KEY, 
     boss_emp_name CHAR(10) REFERENCES OrgChart(emp_name), 
     salary_amt DECIMAL(6,2) DEFAULT 100.00 NOT NULL,
     << horrible cycle constraints >>);
    OrgChart 
    emp_name  boss_emp_name  salary_amt 
    ==============================
    'Albert'    NULL    1000.00
    'Bert'    'Albert'   900.00
    'Chuck'   'Albert'   900.00
    'Donna'   'Chuck'    800.00
    'Eddie'   'Chuck'    700.00
    'Fred'    'Chuck'    600.00
    This approach will wind up with really ugly code -- CTEs hiding recursive procedures, horrible cycle prevention code, etc.  The root of your problem is not knowing that rows are not records, that SQL uses sets and trying to fake pointer chains with some
    vague, magical non-relational "id".  
    This matches the way we did it in old file systems with pointer chains.  Non-RDBMS programmers are comfortable with it because it looks familiar -- it looks like records and not rows.  
    Another way of representing trees is to show them as nested sets. 
    Since SQL is a set oriented language, this is a better model than the usual adjacency list approach you see in most text books. Let us define a simple OrgChart table like this.
    CREATE TABLE OrgChart 
    (emp_name CHAR(10) NOT NULL PRIMARY KEY, 
     lft INTEGER NOT NULL UNIQUE CHECK (lft > 0), 
     rgt INTEGER NOT NULL UNIQUE CHECK (rgt > 1),
      CONSTRAINT order_okay CHECK (lft < rgt));
    OrgChart 
    emp_name         lft rgt 
    ======================
    'Albert'      1   12 
    'Bert'        2    3 
    'Chuck'       4   11 
    'Donna'       5    6 
    'Eddie'       7    8 
    'Fred'        9   10 
    The (lft, rgt) pairs are like tags in a mark-up language, or parens in algebra, BEGIN-END blocks in Algol-family programming languages, etc. -- they bracket a sub-set.  This is a set-oriented approach to trees in a set-oriented language. 
    The organizational chart would look like this as a directed graph:
                Albert (1, 12)
        Bert (2, 3)    Chuck (4, 11)
                       /    |   \
                     /      |     \
                   /        |       \
                 /          |         \
            Donna (5, 6) Eddie (7, 8) Fred (9, 10)
    The adjacency list table is denormalized in several ways. We are modeling both the Personnel and the Organizational chart in one table. But for the sake of saving space, pretend that the names are job titles and that we have another table which describes the
    Personnel that hold those positions.
    Another problem with the adjacency list model is that the boss_emp_name and employee columns are the same kind of thing (i.e. identifiers of personnel), and therefore should be shown in only one column in a normalized table.  To prove that this is not
    normalized, assume that "Chuck" changes his name to "Charles"; you have to change his name in both columns and several places. The defining characteristic of a normalized table is that you have one fact, one place, one time.
    The final problem is that the adjacency list model does not model subordination. Authority flows downhill in a hierarchy, but If I fire Chuck, I disconnect all of his subordinates from Albert. There are situations (i.e. water pipes) where this is true, but
    that is not the expected situation in this case.
    To show a tree as nested sets, replace the nodes with ovals, and then nest subordinate ovals inside each other. The root will be the largest oval and will contain every other node.  The leaf nodes will be the innermost ovals with nothing else inside them
    and the nesting will show the hierarchical relationship. The (lft, rgt) columns (I cannot use the reserved words LEFT and RIGHT in SQL) are what show the nesting. This is like XML, HTML or parentheses. 
    At this point, the boss_emp_name column is both redundant and denormalized, so it can be dropped. Also, note that the tree structure can be kept in one table and all the information about a node can be put in a second table and they can be joined on employee
    number for queries.
    To convert the graph into a nested sets model think of a little worm crawling along the tree. The worm starts at the top, the root, makes a complete trip around the tree. When he comes to a node, he puts a number in the cell on the side that he is visiting
    and increments his counter.  Each node will get two numbers, one of the right side and one for the left. Computer Science majors will recognize this as a modified preorder tree traversal algorithm. Finally, drop the unneeded OrgChart.boss_emp_name column
    which used to represent the edges of a graph.
    This has some predictable results that we can use for building queries.  The root is always (left = 1, right = 2 * (SELECT COUNT(*) FROM TreeTable)); leaf nodes always have (left + 1 = right); subtrees are defined by the BETWEEN predicate; etc. Here are
    two common queries which can be used to build others:
    1. An employee and all their Supervisors, no matter how deep the tree.
     SELECT O2.*
       FROM OrgChart AS O1, OrgChart AS O2
      WHERE O1.lft BETWEEN O2.lft AND O2.rgt
        AND O1.emp_name = :in_emp_name;
    2. The employee and all their subordinates. There is a nice symmetry here.
     SELECT O1.*
       FROM OrgChart AS O1, OrgChart AS O2
      WHERE O1.lft BETWEEN O2.lft AND O2.rgt
        AND O2.emp_name = :in_emp_name;
    3. Add a GROUP BY and aggregate functions to these basic queries and you have hierarchical reports. For example, the total salaries which each employee controls:
     SELECT O2.emp_name, SUM(S1.salary_amt)
       FROM OrgChart AS O1, OrgChart AS O2,
            Salaries AS S1
      WHERE O1.lft BETWEEN O2.lft AND O2.rgt
        AND S1.emp_name = O2.emp_name 
       GROUP BY O2.emp_name;
    4. To find the level and the size of the subtree rooted at each emp_name, so you can print the tree as an indented listing. 
    SELECT O1.emp_name, 
       SUM(CASE WHEN O2.lft BETWEEN O1.lft AND O1.rgt 
       THEN O2.sale_amt ELSE 0.00 END) AS sale_amt_tot,
       SUM(CASE WHEN O2.lft BETWEEN O1.lft AND O1.rgt 
       THEN 1 ELSE 0 END) AS subtree_size,
       SUM(CASE WHEN O1.lft BETWEEN O2.lft AND O2.rgt
       THEN 1 ELSE 0 END) AS lvl
      FROM OrgChart AS O1, OrgChart AS O2
     GROUP BY O1.emp_name;
    5. The nested set model has an implied ordering of siblings which the adjacency list model does not. To insert a new node, G1, under part G.  We can insert one node at a time like this:
    BEGIN ATOMIC
    DECLARE rightmost_spread INTEGER;
    SET rightmost_spread 
        = (SELECT rgt 
             FROM Frammis 
            WHERE part = 'G');
    UPDATE Frammis
       SET lft = CASE WHEN lft > rightmost_spread
                      THEN lft + 2
                      ELSE lft END,
           rgt = CASE WHEN rgt >= rightmost_spread
                      THEN rgt + 2
                      ELSE rgt END
     WHERE rgt >= rightmost_spread;
     INSERT INTO Frammis (part, lft, rgt)
     VALUES ('G1', rightmost_spread, (rightmost_spread + 1));
     COMMIT WORK;
    END;
    The idea is to spread the (lft, rgt) numbers after the youngest child of the parent, G in this case, over by two to make room for the new addition, G1.  This procedure will add the new node to the rightmost child position, which helps to preserve the idea
    of an age order among the siblings.
    6. To convert a nested sets model into an adjacency list model:
    SELECT B.emp_name AS boss_emp_name, E.emp_name
      FROM OrgChart AS E
           LEFT OUTER JOIN
           OrgChart AS B
           ON B.lft
              = (SELECT MAX(lft)
                   FROM OrgChart AS S
                  WHERE E.lft > S.lft
                    AND E.lft < S.rgt);
    7. To find the immediate parent of a node: 
    SELECT MAX(P2.lft), MIN(P2.rgt)
      FROM Personnel AS P1, Personnel AS P2
     WHERE P1.lft BETWEEN P2.lft AND P2.rgt 
       AND P1.emp_name = @my_emp_name;
    I have a book on TREES & HIERARCHIES IN SQL which you can get at Amazon.com right now. It has a lot of other programming idioms for nested sets, like levels, structural comparisons, re-arrangement procedures, etc. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • Select distinct and 2 inner joins in same select statement

    can anyone guide me how to write the below query for higher performance. can I use for all entires or shall i split this,
    please let me know your opinions.
    SELECT DISTINCT werks matnr b~stlal idnrk postp d~aennr
       sortf potx1 c~lkenz b~stlty stlst
       INTO TABLE ltab_one
       FROM mast AS a INNER JOIN stko AS b
         ON  a~stlnr = b~stlnr
         AND a~stlal = b~stlal
         INNER JOIN stas AS c
         ON  b~stlnr = c~stlnr
         AND b~stlal = c~stlal
         AND b~stlty = c~stlty
         INNER JOIN stpo AS d
         ON  c~stlnr = d~stlnr
         AND c~stlkn = d~stlkn
         AND c~stlty = d~stlty
      WHERE a~werks IN s_werks
         AND ( ( d~andat IN s_datum
            OR d~aedat IN s_datum
            OR a~andat IN s_datum
            OR a~aedat IN s_datum
            OR b~andat IN s_datum
            OR b~aedat IN s_datum
            OR c~andat IN s_datum
            OR c~aedat IN s_datum
            ) AND d~datuv >= lv_effdt )
         AND a~stlan = '1'
         AND matnr IN s_matnr.

      WHERE a~werks IN s_werks
         AND ( ( d~andat IN s_datum
            OR d~aedat IN s_datum
            OR a~andat IN s_datum
            OR a~aedat IN s_datum
            OR b~andat IN s_datum
            OR b~aedat IN s_datum
            OR c~andat IN s_datum
            OR c~aedat IN s_datum
            ) AND d~datuv >= lv_effdt )
         AND a~stlan = '1'
         AND matnr IN s_matnr.
    This part determines your performance, not the DISTINCT and not the joins.
    What is in s_werks, s-datum, s_matnr typically? I guess there are better and worse conditions.

  • Select query having count function is returning null

    Hi Everyone,
    Please see the query and help me to get this solved.
    DB version
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - 64bi
    PL/SQL Release 10.2.0.1.0 - Production
    "CORE     10.2.0.1.0     Production"
    TNS for Linux: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - ProductionQUERY
    SELECT COUNT(*) as V_COUNT
          FROM LAB_ORDER_TMPLT_TEST
          WHERE TEST_ID IN
          (SELECT WEST_TEST_ID
                  FROM TEST_CODE_CONVERSION TCC
                  WHERE TCC.EAST_TEST_ID = 2769)
          GROUP BY LAB_ORDER_TMPLT_ID
          HAVING COUNT(*) > 1;
    It's returning null. Is there any way I can get the value as zero instead of null? Please help.Regards,
    BS2012.

    Hi,
    BS2012 wrote:
    Hi Everyone,
    Please see the query and help me to get this solved.
    DB version
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - 64bi
    PL/SQL Release 10.2.0.1.0 - Production
    "CORE     10.2.0.1.0     Production"
    TNS for Linux: Version 10.2.0.1.0 - Production
    NLSRTL Version 10.2.0.1.0 - ProductionQUERY
    SELECT COUNT(*) as V_COUNT
    FROM LAB_ORDER_TMPLT_TEST
    WHERE TEST_ID IN
    (SELECT WEST_TEST_ID
    FROM TEST_CODE_CONVERSION TCC
    WHERE TCC.EAST_TEST_ID = 2769)
    GROUP BY LAB_ORDER_TMPLT_ID
    HAVING COUNT(*) > 1;
    It's returning null.
    Really? COUNT never returns NULL; it always returns 0 or a positive integer.
    Do you mean the query results in "no rows selected"?
    Is there any way I can get the value as zero instead of null? Please help.Do you want a query that will produce the same output as the query above, but will produce a single row containing 0 when the query above does not produce anything? That sounds like a job for an outer join:
    WITH    original_query  AS
           SELECT  COUNT(*) AS v_count
           FROM    lab_order_tmplt_test
           WHERE   test_id IN
                       (   SELECT  west_test_id
                           FROM        test_code_conversion tcc
                           WHERE   tcc.east_test_id = 2769
           GROUP BY  lab_order_tmplt_id
    SELECT     NVL (o.v_count, 0)     AS v_count
    FROM               dual
    LEFT OUTER JOIN  original_query  o  ON  o.v_count > 0
    ;If you'd care to post CREATE TABLE and INSERT statements for the sample data, then I could test this.

  • Query Issue with Inner JOIN

    I need to create the following SQL query in Toplinks, but cannot figure out how to do it. I just want to get all Contacts that have their InitialEventID set to some integer, or have a mapping in the ContactEvents table set to that integer. The mapping between Contacts and ContactEvents is @OnetoMany.
    Select DISTINCT Contacts.* from Contacts JOIN ContactEvents ON (Contacts.ID = ContactEvents.ContactID) WHERE (ContactEvents.EventID = 34 OR Contacts.InitialEventID = 34);
    I'm trying the following, but it obviouly doesn't work.
    SELECT DISTINCT c FROM Contacts c INNER JOIN c.contactEventsCollection ce WHERE ce.eventID = 34
    What should I do?

    Other than the query missing the 'or' clause, why isn't the query working, and what SQL gets generated? You can turn TopLink logging to Fine or Finest to get the SQL logged. You might also want to use OUTER JOIN intead since I assume that Contacts with an InitialEventID=34 may or may not have any ContactEvents associated with it:
    SELECT DISTINCT c FROM Contacts c OUTER JOIN c.contactEventsCollection ce WHERE ( (ce.eventID = 34) OR (c.InitialEventID = 34) )
    Best Regards,
    Chris

  • SQL select query having more than 1000 values in 'IN' clause of predicate.

    Hi,
    We are executing a select query from a table and showing it through a front end screen. When the count of values given in the 'IN' clause of predicate are exceeding 1000 , it is throwing error.
    eg. select * from Employees where emp.Id. in('111',123','121','3232',........1001 Ids)
    We are using Oracle version 10.2.0.
    Please suggest how to tackle such issue.
    Regards,
    Naveen Kumar.C.
    Edited by: Naveen Kumar C on Aug 30, 2008 10:01 PM

    Use a nested table:
    create or replace type numbertype
    as object
    (nr number(20,10) )
    create or replace type number_table
    as table of numbertype
    create or replace procedure tableselect
    ( p_numbers in number_table
    , p_ref_result out sys_refcursor)
    is
    begin
    open p_ref_result for
         select *
    {noformat}     from   employees
         ,        (select /*+ cardinality(tab 10) */ tab.nr
                   from   table(p_numbers) tab) tbnrs
         where id = tbnrs.nr;
    end;
    /{noformat}
    Using nested tables will reduce the amount of parsing because the sql statement uses binded variables! The cardinality hint causes Oracle to use the index on employees.id.

  • Need help in writing a select query to pull required data from 3 tables.

    Hi,
    I have three tables EmpIDs,EmpRoles and LatestRoles. I need to write a select Query to get roles of all employees present in EmpIDs table by referring EmpRoles and LatestRoles.
    The condition is first look into table EmpRoles and if it has more than one entry for a particular Employee ID than only need to get the Role from LatestRoles other wise consider
    the role from EmpRoles .
    Sample Script:
    Create Table #EmpIDs
    (EmplID int )
    Create Table #EmpRoles
    (EMPID int,Designation varchar(50))
    Create Table #LatestRoles
    EmpID int,
    Designation varchar(50)
    Insert into #EmpIDs values (1),(2),(3)
    Insert into #EmpRoles values (1,'Role1'),(2,'Role1'),(2,'Role2'),(3,'Role1')
    Insert into #LatestRoles values (2,'Role2')
    Employee ID 2 is having two roles defined in EmpRoles so for EmpID 2 need to fetch Role from LatestRoles table and for
    remaining ID's need to fetch from EmpRoles .
    My Final Output of select query should be like below.
    EmpID Role
    1 Role1
    2 Role2
    3 Role1
    Please help.
    Mohan

    Mohan,
    Can you check if this answers your requirement:
    Create Table #EmpIDs
    (EmplID int )
    Create Table #EmpRoles
    (EMPID int,Designation varchar(50))
    Create Table #LatestRoles
    EmpID int,
    Designation varchar(50)
    Insert into #EmpIDs values (1)
    Insert into #EmpIDs values (2)
    Insert into #EmpIDs values (3)
    Insert into #EmpRoles values (1,'Role1')
    Insert into #EmpRoles values (2,'Role2')
    Insert into #EmpRoles values (2,'Role1')
    Insert into #EmpRoles values (3,'Role1')
    Insert into #LatestRoles values (2,'Role2')
    --Method 1
    select e.EmplID,MIN(ISNULL(l.Designation,r.Designation)) as Designation
    from #empids e
    left join #emproles r on e.emplID=r.EmpID
    left join #latestRoles l on e.emplID=l.EmpID
    group by e.EmplID
    --Method 2
    ;with cte
    as
    select distinct e.EmplID,r.Designation,count(*) over(partition by e.emplID) cnt
    from #empids e
    left join #emproles r on e.emplID=r.EmpID
    select emplID,Designation
    from cte
    where cnt=1
    UNION ALL
    select a.EmplID,l.Designation
    from
    (select distinct EmplID from cte where cnt>1) a
    join #Latestroles l on a.EmplID=l.EmpID
    order by emplID
    Thanks,
    Jay
    <If the post was helpful mark as 'Helpful' and if the post answered your query, mark as 'Answered'>

  • Inner Join of 3 tables is correct or not?

    Hi Guys ,
                 I have a requirement where i have to join 3 tables i  dont know whether the inner Join which i wrote for 3 tables is correct or not.I am not getting any Syntax error but whether the logci below which i wrote gets all the records or not.
    The Requirement is
    "c.     Select the BOL Number entered in the screen and query the table LIKP with the BOL number in the field LIKP-BOLNR.  Gather the list of ALL delivery documents (LIKP-VBELN) that is outputted.
    d.     Query the list of the delivery documents obtained into the table VBFA in the field VBFA- VBELV.  From the output that is displayed, select the Follow-On Document Field (VBFA-VBELN) for that item whose Subsequent Document Category (VBFA- VBTYP_N) is R and the Movement Type (VBFA- BWART) is 641.  Get the Follow-On document number for each of the above Delivery Document number.
    e.     Query the table EKBE with the Follow On document obtained above in the field Material Document (EKBE- BELNR).  Perform this activity for each of the follow on document obtained above.  Get the resultant Purchase Order (EKBE-EBELN) and Item Number (EKBE-EBELP) from the query.  After querying will all the Follow-On Documents, get the unique list of PO number and Item Number.
    The logic which i wrote is
                    Begin of t_PoolSTO_out,
                  BOLNR type LIKP-BOLNR,
                  EBELN type EKBE-EBELN,
                  EBELP type EKBE-EBELP,
                  VBELN type LIKP-VBELN,
                  VBELNV type VBFA-VBELN,
             End of t_PoolSTO_out.
          Data: i_PoolSTO type Standard table of t_PoolSTO_out.
      Select
            a~BOLNR
            c~EBELN
            c~EBELP
            a~VBELN
            b~VBELN
            from LIKP as a
            Inner Join VBFA as b on aVBELN = bVBELV
            Inner Join EKBE as c on bVBELN = cBELNR
            into Table i_PoolSTO
            Where a~BOLNR in S_LBLNE and
                  b~VBTYP_N = 'R' and
                  b~BWART = '641'.
              My doubt is whether the logic works or not i Mean does i getall the rrecords based on the requirement.?
                      If not please tell any alternative logic?
    Thanks,
    Gopi Anne.

    Hi Gopi,
    Your code is Good.
    But try to avoid Inner join with more number of Tables ...because this is a performance issue..
    try to use..
    select (primary key fields mainly,other fields) from LIKP into itab where bolnr in p_bolnr(paramater).
    next try to use for all entries option..
    select (primary key fields mainly,other fields) from VBFA for all entries in itab where (give the condition)....
    simillarly do for the other select ....ok this will try to reduce the performance issue....
    <b><REMOVED BY MODERATOR></b>
    Message was edited by:
            Alvaro Tejada Galindo

  • Inner join on four tables

    hi all,
    i am facing the problem with the inner join in the select query for 4 tables.
    can i use the inner join for tables in SAP 6.0 version,
    it is going to dump.
    here is my code
    SELECT DISTINCT apernr abegda aendda awagetype aamount acurrency
            altrctry brufnm banred bvorna bnachn cgroupcode d~vdsk1
    FROM pa9011 AS a INNER JOIN pa0002 AS b ON bpernr = apernr
                      INNER JOIN pa9013 AS c ON cpernr = bpernr
                      inner join pa0001 as d on dpernr = cpernr
                      INTO CORRESPONDING FIELDS OF TABLE it_bonus
    WHERE a~pernr IN s_pernr AND
           a~begda IN s_date AND
           a~subty EQ s_subty AND
           a~wagetype EQ wa_perbonus AND
           a~ltrctry = gc_ind AND
           a~amount > 0 AND
           b~endda = '99991231' AND
           c~groupcode IN s_loc AND
           c~endda = '99991231' and
           d~endda = '99991231'
        ORDER BY a~pernr.

    hi this is the dump ,
    In a SELECT access, the read file could not be placed in the target
    field provided.
    Either the conversion is not supported for the type of the target field,
    the target field is too small to include the value, or the data does not
    have the format required for the target field.

  • Inner joins on the tables VAKPA , VBAP and KNA1

    HI ,
    I have one performance issue.please see the below select query..In order to improve the performance i need to change this select query with out changing the functionality.Can any one of you please suggest me .
       SELECT vakpakunde vakpaparvw kna1kunnr kna1name1 kna1~ktokd
               vbapvbeln vbapposnr vbaparktx vbapzzclass
               vbapmvgr2 vbapmvgr3 vbapmvgr5 vbapzzcanvas_year
               vbapmatnr vbapmatkl
         FROM  vakpa
         INNER JOIN  vbap ON
               vakpavbeln = vbapvbeln
         INNER JOIN kna1 ON
               vakpakunnr = kna1kunnr
         INTO CORRESPONDING FIELDS OF TABLE gt_vbap
         WHERE vakpa~kunde IN so_kunnr
         AND   vakpa~parvw = 'AG'
         AND   vakpa~vkorg IN so_vkorg
         AND ( vbap~zzad_line_status = 'PR' OR
               vbap~zzad_line_status = 'RE' )
         AND   vbap~mvgr5         IN r_ctf
         AND   vbap~matkl         IN so_matkl
         AND   vbap~matnr         IN so_matnr
         AND   vbap~zzcanvas_year IN so_year.
      ENDIF.

    Use FOR ALL ENTRIES statement instead of joints.
    or
    and Remove INTO CORRESPONDING FIELDS by selecting the fields in the orderstored in table
    Edited by: kalandar on Dec 4, 2009 7:43 AM

Maybe you are looking for

  • Windows 7 Home Premium 64 Bit activation problems ( 0xC004E003 )

    I just fixed my old computer that crashed years ago (windows xp).  Windows 7 Home Premium works find just cant get it to activate every time i enter the key it loads all the way then I get an error code ( 0xC004E003 ).  What can I do to fix?  Calling

  • Error Integrating EWS 2.2 with Windows Phone 8.1 App

    Hi, I am new to Windows Phone development. I have a basic need to access the Exchange Calendar. I am using Windows Phone 8.1 SDK and Exchange Web Service 2.2 SDK. As a first step I tried to use the Microsoft.Exchange.WebServices.Autodiscover dll to f

  • Need a way to get downloads option from safari on dock.

    I accidentally deleted my downloads option for safari on my dock. It is also no longer in my finder. Is there a way for me to get it back?

  • Approval Report

    dear all, is there a universal table in which all the approvals are recorded (pending or approved). a quick response would be appreciated. thanks. regards, sidharth

  • Error on OS language in Netweaver Installation

    Dear all, I want to install an SAP Netweaver JAVA BI (JAVA only) but in the installation process there comes a message that the user groups are in german and they must be in english. After the change of the system language to english the user groups