Subquery in Select Statement

Hi,
In crystal reports 10 is there a way to alter the select statement to include a subquery into the select statement.  For example
select customer.lastname from customer;
to be
select customer.lastname , (select departmentname from dept where customer.dept_id= dept.dept_id) as "Customer_DeptName"
from customer;
I don't know how to do this in crystal but this can easily be done in toad or other sql query tool.
Please advise.
Thanks.
Tom.

hi Tom,
i walk through how to create a sub select (using a command object instead of using tables) in this post here...
http://scn.sap.com/community/crystal-reports/blog/2012/07/11/show-all-sub-groups-and-a-summary-for-every-group
cheers,
jamie

Similar Messages

  • USING SUBQUERY IN SELECT STATEMENT

    I am looking at reusing the results of a first query in a second select statement.
    I have a first table "ACTIVE_FIELDS" in which I maintain the columns I want to query.
    Table name ACTIVE_FIELDS
    Field - Status
    CODE - ACTIVE
    DESCRIPTION - ACTIVE
    NAME - INACTIVE
    So I get the list of active fields by doing :
    SELECT FIELD FROM ACTIVE_FIELDS WHERE STATUS=ACTIVE
    It gives me : Code and Description.
    I have then a second table MATERIAL with 3 columns CODE, DESCRIPTION and NAME.
    I am looking at doing a query against MATERIAL table as follows
    SELECT (SELECT FIELD FROM ACTIVE_FIELDS WHERE STATUS=ACTIVE) from MATERIAL and I expect to only get columns CODE and DESCRIPTION in the result.
    If I want to add the NAME field in the result of my query, I just have to change status of NAME field in the eh ACTIVE_FIELDS table..
    Can anybody help me with the exact syntax, I must miss a function to convert the result of the first query..

    that data model looks suspiciously like an attribute-value generic model, thus the need for that funky sql.
    read this thread.
    Re: SIMPLE Database Design Problem !

  • How to model in OWB if you have a subquery in your select statement? (11.2)

    Which operator (is it the Table operator) to use if I have a subquery as part of my select statement? (The way I do it works, but is not elegant. What I do is create a table for the subquery and than join that with the other sources to point to my target.) But, would appreciate the best way with OWB's features.
    Here is the entire SQL (including the subquery):
    SELECT to_numbe (null), course_id
    at.book, lp.NAME,
    (select b.pricing from qp_pricing_attributes b
    where b.list_id = ll.list_id and b.product = at.product) sign,
    ll.operand AS price, lhb.comments
    FROM
    pricing_attribs at,
    list_lines ll,
    list_h lp,
    list_b lhb
    WHERE 1 = 1
    and ll.list_line_id = atrib.list_line_id
    AND ll.list_header_id = lp.list_header_id
    AND lp.list_header_id = lhb.list_header_id
    Thanks you.

    Hi
    Doesn't need to be a table in the target. Let's take a very simple example, let's say you wanted to do the following;
    select ename,(select dname from dept d where d.deptno=e.deptno) from emp e
    Then DEPT is your lookup table and EMP is your driving table.
    1. Add EMP on to the canvas.
    2. Add in lookup operator
    3. Bind lookup to DEPT
    4. Hit finish
    5. Map EMP.DEPT to DEPT.INGRP1 (the lookup operator)
    6. Edit lookup operator, on Lookup Conditions tab set DEPTNO for lookup column, and DEPTNO for input attribute
    7. Lookup complete now
    You can add in a target table operator and map from the source EMP table and the output attributes of the lookup operator. you can change step 4 to carry on through wizard and define lookup, but I have chosen to do 5, to automatically get the names and datatypes of the inputs. There are lot of other options now in 11gR2 in the lookup.
    Hope this makes sense.
    Cheers
    David

  • Sql Error in Select statement when doing subquery

    Hi,
    I am trying to see what the error is in the subquery part of the select statement.
    Subquery should be fetching the safety_stock_quantity based on the MAX(effectivity_date).
    Any suggestions?
    SELECT kbn.last_update_date,itm.segment1,itm.description,kbn.kanban_card_number,kbn.kanban_size,
                   (SELECT msc.safety_stock_quantity
    FROM mtl_safety_stocks msc
    WHERE msc.effectivity_date = (select MAX(msc2.effectivity_date)
                   from mtl_safety_stocks msc2
                                            where msc2.inventory_item_id = itm.inventory_item_id
                                                 and msc2.organization_id = itm.organization_id)
                   AND msc.inventory_item_id = itm.inventory_item_id
         AND msc.organization_id = itm.organization_id                                        
    FROM mtl_system_items_b itm
    ,mtl_onhand_quantities_detail moqd
              ,mtl_safety_stocks msc
              ,mtl_kanban_card_activity kbn
    WHERE itm.inventory_item_id = kbn.inventory_item_id
    AND itm.organization_id = kbn.organization_id
    AND itm.inventory_item_id = moqd.inventory_item_id
    AND itm.organization_id = moqd.organization_id
    AND moqd.subinventory_code = kbn.source_subinventory
         AND kbn.card_status = 1
         AND kbn.supply_status = 5
         AND msc.inventory_item_id = itm.inventory_item_id
         AND msc.organization_id = itm.organization_id     
    GROUP BY
    kbn.last_update_date,itm.segment1,itm.description,kbn.kanban_card_number,kbn.kanban_size;
    Thanks
    Pravn

    Hi, Pravn,
    Remember the ABC's of GROUP BY:
    When you use a GROUP BY clause and/or an aggregate fucntion, then every item in the SELECT clause must be:
    (A) an <b>A</b>ggregate function,
    (B) one of the "group <b>B</b>y" expressions,
    (C) a <b>C</b>onstant, or
    (D) something that <b>D</b>epends entirely on the above. (For example, if you "GROUP BY TRUNC(dt)", you can "SELECT TO_CHAR (TRUNC(dt), 'Mon-DD')").
    There's a GROUP BY clause in your main query, so every item in the main SELECT clause must be one of the above. The last item, the unnamed scalar sub-query, is none of the above.
    How can you fix this problem? That depends on your data, the results you want, and perhaps on your Oracle version. If you'd like help, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved. Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    Always say which version of Oracle you're using.
    You may have noticed that this site normally doesn't display multiple spaces in a row.
    Whenever you post formatted text (including, but limited to, actual code) on this site, type these 6 characters:
    \(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Subquery in IN clause of an select statement

    Hi friends,
    The Subquery in IN clause of an select statement take long time , is there any alternate ??
    >select * from oudata.SURVEY_USER_ANSWERS
    >where user_id in (select user_id from oudata.SURVEY_USERS where trunc(course_start_date) <'01-Jun-2007');
    thnaks,
    raj
    Edited by: infant_raj on May 28, 2009 12:09 AM

    infant_raj wrote:
    Hi friends,
    The Subquery in IN clause of an select statement take long time , is there any alternate ??
    select * from oudata.SURVEY_USER_ANSWERS
    where user_id in (select user_id from oudata.SURVEY_USERS where trunc(course_start_date) <'01-Jun-2007');
    No database version specified?
    No table structures/indexes given?
    No indication of the cardinality, selectivity, skew of the data being queried.
    Have you got a function based index for "trunc(course_start_date)"?
    Why are you not specifying your comparison date as a DATE datatype rather than relying on implicit conversion? i.e. it should be "to_date('01-Jun-2007','DD-MON-YYYY')"
    Have statistics been gathered on the data
    [How to post a SQL statement tuning request|http://forums.oracle.com/forums/thread.jspa?threadID=863295&tstart=0]
    [When your query takes too long...|http://forums.oracle.com/forums/thread.jspa?messageID=1812597#1812597]

  • Using Select statement in IF condition?

    hi all,
    Can i use select statement in IF COndition in pl sql ?
    eg like- if( select 1 from ASD) then
    end if;

    There is no way to do any kind of select statement inside if conditions.
    Why don't test simple cases like this first?
    An example to show it.
    SQL> begin
      2   if exists (select 1 from dual) then
      3    dbms_output.put_line('ok');
      4   end if;
      5  end;
      6  /
    if exists (select 1 from dual) then
    ERRORE alla riga 2:
    ORA-06550: line 2, column 5:
    PLS-00204: function or pseudo-column 'EXISTS' may be used inside a SQL
    statement only
    ORA-06550: line 2, column 2:
    PL/SQL: Statement ignored
    SQL> begin
      2   if ( (select count(*) from dual) > 0 ) then
      3    dbms_output.put_line('ok');
      4   end if;
      5  end;
      6  /
    if ( (select count(*) from dual) > 0 ) then
    ERRORE alla riga 2:
    ORA-06550: line 2, column 8:
    PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:
    ( - + case mod new not null others <an identifier>
    <a double-quoted delimited-identifier> <a bind variable> avg
    count current exists max min prior sql stddev sum variance
    execute forall merge time timestamp interval date
    <a string literal with character set specification>
    <a number> <a single-quoted SQL string> pipe
    <an alternatively-quoted string literal with character set specification>
    <an alternativ
    ORA-06550: line 2, column 33:
    PLS-00103: Encountered the symbol ")" when expecting one of the following:
    . , @ ; for <an identifier>
    <a double-quoted delimited-identifier> group having intersect
    minus order partition start subpartition union where connect
    SQL> begin
      2   if ( 0 in (select count(*) from dual) ) then
      3    dbms_output.put_line('ok');
      4   end if;
      5  end;
      6  /
    if ( 0 in (select count(*) from dual) ) then
    ERRORE alla riga 2:
    ORA-06550: line 2, column 12:
    PLS-00405: subquery not allowed in this context
    ORA-06550: line 2, column 2:
    PL/SQL: Statement ignoredBye Alessandro

  • How can i use multiple row subquery in update statement

    Hai All
    I using group function in my update statement.. and i need to update more rows so i need to use multiple row
    subquery pls tell me how to use multiple row subquery in update statement
    For example
    while i am using this like this i got an error
    update dail_att set outtime in (select max(r2.ptime) from temp_att where empcode=r2.enpno and
    barcode=r2.cardn and attend_date=r2.pdate group by enpno,pdate,cardn);
    Pls tell me how to use with example
    Thanks & regards
    Srikkanth.M

    Hai Man
    Thanks for ur response Let me clear what i need
    First step Fetch the records as text file and stores into table T1
    and the next step is i have seperated the text using substring and stores in different columns of a table
    There are two shifts 0815 to 1645 and 1200 and 2000
    Here I rep IN and O rep OUT
    Empno date time inout
    001 01-01-10 0815 I
    002 01-01-10 0815 I
    003 01-01-10 0818 I
    001 01-01-10 1100 0
    001 01-01-10 1130 I
    002 01-01-10 1145 0
    002 01-01-10 1215 I
    004 01-01-10 1200 I
    005 01-01-10 1215 I
    004 01-01-10 1315 O
    004 01-01-10 1345 I
    001 01-01-10 1645 0
    002 01-01-10 1715 0
    003 01-01-10 1718 0
    004 01-01-10 2010 0
    005 01-01-10 2015 0
    This is my T1 table i have taken data from text file and stored in this table from this table i need to move data to another table T2
    T2 contains like this
    Empno Intime Intrin Introut Outtime Date
    001 0815 1100 1130 1645 01-01-10
    002 0815 1145 1215 1715 01-01-10
    003 0818 1718 01-01-10
    004 1200 1315 1345 2010 01-01-10
    005 1215 2015 01-01-10
    This what i am trying to do man but i have little bit problems Pls give some solution with good example
    And my coding is
    declare
         emp_code varchar2(25);
    in_time varchar2(25);
    out_time varchar2(25);
    Cursor P1 is
    Select REASON,ECODE,READMODE,EMPD,ENPNO,FILL,PDATE,PTIME,INOUT,CARDN,READERN
    From temp_att
    group by REASON,ECODE,READMODE,EMPD,ENPNO,FILL,PDATE,PTIME,INOUT,CARDN,READERN
    ORDER BY enpno,pdate,ptime;
    begin
         for r2 in p1 loop
    declare
    bar_code varchar2(25);
    begin
    select barcode into bar_code from dail_att where empcode=r2.enpno and attend_date=r2.pdate;
    For r3 in (select empcode,empname,barcode,intime,intrin,introut,addin,addout,outtime,attend_date from dail_att)loop
    if r2.inout ='O' then
    update dail_att set outtime =(select max(r2.ptime) from temp_att where empcode=r2.enpno and barcode=r2.cardn and attend_date=r2.pdate group by r2.cardn,r2.enpno,r2.pdate );
    end if;
    end loop;     
    exception
         when no_data_found then
         if r2.inout ='I' then
                   insert into dail_att(barcode,empcode,intime,attend_date)(select r2.cardn,r2.enpno,min(r2.ptime),r2.pdate from temp_att group by r2.cardn,r2.enpno,r2.pdate );
         end if;
    end;
    end loop;
    commit;     
         end;
    Pls tell me what correction i need to do i the update statement i have used a subquery with group function but when i used it will return only one row but my need is to return many rows and i need to use multiple row subquery
    and how can i use it in the update statement
    Thanks In Advance
    Srikkanth.M

  • Subquery in SELECT list vs join

    If I'm not mistaken, both queries below are functionally the same. Both return all rows from table1 and only show a value for table2.F7 if the first 4 characters of F7 equal F2.
    My thoughts are this... It's nice that a subquery can be used in a select list, but it looks like, with all the sql I've written which uses that approach, I could have just as well used the join approach. Is this always true? Can someone show me as example where using a subquery in the select list is hands-down the better approach?
    SELECT table1.F2,
    (SELECT table2.F7 FROM table2 WHERE substr(table2.F7,1,4) = table1.F2)
    FROM table1
    SELECT table1.F2, table2.F7
    FROM table1, table2
    WHERE table1.F2 = substr(table2.F7,1,4)(+)
    Let me add that, in my top example, multiple rows will never be returned by the subquery. If that were the case, then the join approach would be the only option.
    Message was edited by:
    Nick2012

    Probably there is no general answer and you'll always have to check separately.
    In the following example the scalar subquery turns out to be slightly more efficient than an outer join (15 gets versus 13 gets and compare the elapsed time):
    SQL> SET autotrace traceonly explain statistics
    SQL> SET timing on
    SQL>
    SQL> SELECT ename, (SELECT dname
      2                   FROM dept d
      3                  WHERE d.deptno = e.deptno) dname
      4    FROM emp e
      5  /
    14 rows selected.
    Elapsed: 00:00:00.72
    Execution Plan
    Plan hash value: 2981343222
    | Id  | Operation                   | Name    | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT            |         |    15 |   135 |     3   (0)| 00:00:01 |
    |   1 |  TABLE ACCESS BY INDEX ROWID| DEPT    |     1 |    11 |     1   (0)| 00:00:01 |
    |*  2 |   INDEX UNIQUE SCAN         | PK_DEPT |     1 |       |     0   (0)| 00:00:01 |
    |   3 |  TABLE ACCESS FULL          | EMP     |    15 |   135 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       2 - access("D"."DEPTNO"=:B1)
    Statistics
              0  recursive calls
              0  db block gets
             13  consistent gets
              0  physical reads
              0  redo size
            742  bytes sent via SQL*Net to client
            381  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
             14  rows processed
    SQL> SELECT ename, dname
      2    FROM emp e, dept d
      3   WHERE d.deptno(+) = e.deptno
      4  /
    14 rows selected.
    Elapsed: 00:00:00.74
    Execution Plan
    Plan hash value: 3387915970
    | Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT   |      |    15 |   300 |     7  (15)| 00:00:01 |
    |*  1 |  HASH JOIN OUTER   |      |    15 |   300 |     7  (15)| 00:00:01 |
    |   2 |   TABLE ACCESS FULL| EMP  |    15 |   135 |     3   (0)| 00:00:01 |
    |   3 |   TABLE ACCESS FULL| DEPT |     5 |    55 |     3   (0)| 00:00:01 |
    Predicate Information (identified by operation id):
       1 - access("D"."DEPTNO"(+)="E"."DEPTNO")
    Statistics
              0  recursive calls
              0  db block gets
             15  consistent gets
              0  physical reads
              0  redo size
            666  bytes sent via SQL*Net to client
            381  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              0  sorts (memory)
              0  sorts (disk)
             14  rows processed

  • Problem with SELECT statement. What is wrong with it?

    Why is this query....
    <cfquery datasource="manna_premier" name="kit_report">
    SELECT Orders.ID,
           SaleDate,
           Orders.UserID,
        Distributor,
        DealerID,
        Variable,
        TerritoryManager,
        US_Dealers.ID,
           DealerName,
        DealerAddress,
        DealerCity,
        DealerState,
        DealerZIPCode,
        (SELECT SUM(Quantity)
         FROM ProductOrders PO
         WHERE PO.OrderID = Orders.ID) as totalProducts,    
    FROM Orders, US_Dealers
    WHERE US_Dealers.ID = DealerID AND SaleDate BETWEEN #CreateODBCDate(FORM.Start)# AND #CreateODBCDate(FORM.End)# AND Variable = '#Variable#'
    </cfquery>
    giving me this error message...
    Error Executing Database Query.
    [Macromedia][SequeLink JDBC Driver][ODBC Socket][Microsoft][ODBC Microsoft Access Driver] The SELECT statement includes a reserved word or an argument name that is misspelled or missing, or the punctuation is incorrect.
    The error occurred in D:\Inetpub\mannapremier\kit_report2.cfm: line 20
    18 :              WHERE PO.OrderID = Orders.ID) as totalProducts,        
    19 : FROM Orders, US_Dealers
    20 : WHERE US_Dealers.ID = DealerID AND SaleDate BETWEEN #CreateODBCDate(FORM.Start)# AND #CreateODBCDate(FORM.End)# AND Variable = '#Variable#'
    21 : </cfquery>
    22 :
    SQLSTATE
      42000
    SQL
       SELECT Orders.ID, SaleDate, Orders.UserID, Distributor, DealerID, Variable, TerritoryManager, US_Dealers.ID, DealerName, DealerAddress, DealerCity, DealerState, DealerZIPCode, (SELECT SUM(Quantity) FROM ProductOrders PO WHERE PO.OrderID = Orders.ID) as totalProducts, FROM Orders, US_Dealers WHERE US_Dealers.ID = DealerID AND SaleDate BETWEEN {d '2009-10-01'} AND {d '2009-10-31'} AND Variable = 'Chick Days pre-book'
    VENDORERRORCODE
      -3504
    DATASOURCE
      manna_premier
    Resources:
    I copied it from a different template where it works without error...
    <cfquery name="qZVPData" datasource="manna_premier">
    SELECT UserID,
           TMName,
        UserZone,
              (SELECT COUNT(*)
               FROM Sales_Calls
               WHERE Sales_Calls.UserID = u.UserID) as totalCalls,
        (SELECT COUNT(*)
         FROM Orders
         WHERE Orders.UserID = u.UserID) as totalOrders,
        (SELECT SUM(Quantity)
         FROM ProductOrders PO
         WHERE PO.UserID = u.UserID AND PO.NewExisting = 1) as newItems,
        (SELECT SUM(NewExisting)
         FROM  ProductOrders PO_
         WHERE PO_.UserID = u.UserID) as totalNew,
        SUM(totalOrders)/(totalCalls) AS closePerc
    FROM Users u
    WHERE UserZone = 'Central'
    GROUP BY UserZone, UserID, TMName
    </cfquery>
    What is the problem?

    It's hard to say: what's your request timeout set to?
    700-odd records is not much of a fetch for a decent DB, and I would not expect that to case the problem.  But then you're using Access which doesn't fit the description of "decent DB" (or "fit for purpose" or "intended for purpose"), so I guess all bets are off one that one.  If this query is slow when ONE request is asking for it, what is going to happen when it goes live and multiple requests are asking for it, along with all the other queries your site will want to run?  Access is not designed for this.  It will really struggle, and cause your site to run like a dog.  One that died serveral weeks ago.
    What else is on the template?  I presume you're doing something with the query once you fetch it, so could it be that code that's running slowly?  Have you taken any steps to isolate which part of the code is taking so long?
    How does the query perform if you take the subquery out of the select line?  Is there any other way of getting that data?  What subquery will be running once for every row of the result set... not very nice.
    Adam

  • SELECT statement comparing 2 fields in a table.

    Hi,
    Can someone help me out  in making a efficient SELECT statement for the follwing requirement.
    Say, I want to select all the records from a database table where the field, PLANT is equal to field SALESORG in the table (i.e., when both fields are equal select that record).
    Thanks & regards,
    Sree

    Hello,
    I think this is the answer to your question... if you explain a bit more we can formulate a query.
    Subquery
    Variants:
    1. ( select )
    2. ALL ( select )
    3. ANY ( select )
    4. SOME ( select )
    Effect
    A subquery is a SELECT statement select that occurs within a
    SELECT,
    OPEN CURSOR,
    UPDATE, or
    DELETE statement
    in the WHERE clause or HAVING clause, to check whether data from database tables or views meets certain criteria.
    Subqueries have a restricted syntax in comparison to the normal SELECT statement:
    SELECT result FROM source [WHERE where] [GROUP BY fields]       [HAVING having].
    Variant 1
    ( select )
    If the subquery returns a single value, you can use any relational operator except LIKE and BETWEEN.
    Example
    Selecting the flights with the most passengers:
    DATA: WA TYPE SFLIGHT.
    SELECT * FROM SFLIGHT
        INTO WA
        WHERE SEATSOCC = ( SELECT MAX( SEATSOCC ) FROM SFLIGHT ).
      WRITE: / WA-CARRID, WA-CONNID, WA-FLDATE.
    ENDSELECT.
    Note
    If you use a subquery with a relational operator instead of EXISTS, you may only specify one column in the SELECT clause. This can be either a field from the database table or an aggregate expression. Subqueries of this kind are referred to as scalar subqueries.
    Variant 2
    ALL ( select )
    If the subquery returns several lines, each containing one value, you specify that the comparison should apply for all of the values it returns.
    Example
    This example shows how to use ALL. It displays a list of the customer IDs of the customer (or customers) who have made the most bookings:
    DATA: ID TYPE SBOOK-CUSTOMID, CNT TYPE I.
    SELECT CUSTOMID COUNT( * ) AS C FROM SBOOK
        INTO (ID, CNT)
        GROUP BY CUSTOMID
        HAVING COUNT( * ) >=
          ALL ( SELECT COUNT( * ) FROM SBOOK GROUP BY CUSTOMID ).
      WRITE: / ID, CNT.
    ENDSELECT.
    Variant 3
    ANY ( select )
    Variant 4
    SOME ( select )
    If the subquery returns several lines each containing one value, this variant specifies that the comparison should apply to at least one of the values returned. The IN operator is the same as the combination = ANY.
    &ABAP_HINT
    If you use a subquery with the EXISTS operator, the expression is true if the subquery selects at least one line. You can useuse * in the SELECT clause of subqueries that use EXISTS.
    Example
    Selecting all flights from Frankfurt to New York between 1.1.1999 and 31.3.1999 that are not yet full:
    DATA: WA_SFLIGHT TYPE SFLIGHT.
    SELECT * FROM SFLIGHT AS F INTO WA_SFLIGHT
        WHERE SEATSOCC < F~SEATSMAX
          AND EXISTS ( SELECT * FROM SPFLI
                        WHERE CARRID = F~CARRID
                           AND CONNID = F~CONNID
                           AND CITYFROM = 'FRANKFURT'
                           AND CITYTO = 'NEW YORK' )
          AND FLDATE BETWEEN '19990101' AND '19990331'.
      WRITE: / WA_SFLIGHT-CARRID, WA_SFLIGHT-CONNID,
               WA_SFLIGHT-FLDATE.
    ENDSELECT.
    Subqueries such as the one in this example, in which the WHERE clause uses fields from the main query, are known as correlated subqueries. Subqueries can be nested, and a given subquery may contain any fields from other, hierarchically-superior subqueries.
    In a correlated subquery, the subquery is executed for each line r returned by the main query. In the above example, the main query finds all flights in table SFLIGHT that are not full and that have a date that meets the selection criterion. The statement then performs the subquery for each of the records returned by the main query, using the corresponding values of CARRID and CONNID, to check whether the relevant flight operates between Frankfurt and New York.
    Additional help
    Subqueries

  • Limit rows in select statement

    Hi,
    we have the following SQL select statement in an extension in our CMS system
    var newConn = new openConnection();
    if(request.searchBox)
         var searchBox = request.searchBox;
         var keywords = searchBox.split(' ')
         var sql = 'SELECT forumID, masterID, subject, message, datePosted FROM THREADS WHERE approved=1'
         for(var i=0; i<keywords.length; i++)
              sql += ' AND UPPER(subject) LIKE UPPER(\'%' + keywords[i] + '%\')'
              sql += ' OR UPPER(message) LIKE UPPER(\'%' + keywords[i] + '%\')'
         sql          += ' ORDER BY datePosted DESC;';
    else {
         document.write("No results found");
    var result = newConn.execute(sql);
    var counter = 0;
    while(result && (counter < 5 || request.searchBox))
         ascii_nextCol(result[0]);                                             //Datafield 0 Forum ID
         ascii_nextCol(result[1]);                                             //Datafield 1 Master ID
         ascii_nextCol(result[2]);                                             //Datafield 2 Subject
         ascii_nextCol(result[3]);                                             //Datafield 3 Message
         ascii_nextCol(dateFormatter.format(result[4]));                    //Datafield 4 Date posted     
         ascii_nextRow();
         result = newConn.nextRow();
         counter++;
    closeConnection(newConn);
    ascii_update();
    There are a couple of issues with it though, this bit doesn't work when no results are returned:
    else {
         document.write("No results found");
    And I want to limit the number of rows to 50.
    Someone mentioned that "ROWCOUNT" could be the answer to both problems but I have no idea where it should go or how to write it into this code. I've tried Googling for an answer without much luck as I don't know a great deal about this coding.
    Can anyone help?

    Aga wrote:
    Try adding
    sql += ' AND rownum < 51'
    before
    sql += ' ORDER BY datePosted DESC;';
    It will limit the number of rows to 50.If you limit by rownum and order in the same query you are ordering 50 random rows of the query.
    you should order in a subquery before using rownum to get only the top results.
    Processing ...
    with t as (
         select 120 as val from dual
         union all
         select -5 as val from dual
         union all
         select 45 as val from dual
         union all
         select 3 as val from dual
         union all
         select 1258 as val from dual
         union all
         select 874552 as val from dual
         union all
         select -1452 as val from dual
         union all
         select 0 as val from dual
    select *
    from t
    where rownum <= 3
    order by val
    Query finished, retrieving results...
                      VAL                 
                                        -5
                                        45
                                       120
    3 row(s) retrieved
    Processing ...
    with t as (
         select 120 as val from dual
         union all
         select -5 as val from dual
         union all
         select 45 as val from dual
         union all
         select 3 as val from dual
         union all
         select 1258 as val from dual
         union all
         select 874552 as val from dual
         union all
         select -1452 as val from dual
         union all
         select 0 as val from dual
    select *
    from (
              select *
              from t
              order by val
    where rownum <= 3
    Query finished, retrieving results...
                      VAL                 
                                     -1452
                                        -5
                                         0
    3 row(s) retrievedBye Alessandro

  • Can call a function in the select statement?

    Is there any ways to call a function in the select statement?
    what I like to do is this:
    select deptno, totalEmployees(deptno), TotalSalary(deptno)
    from emp;
    I know it can be done by count(*) and join tables, but my case
    is much more complex and the where clauses are different from
    one function to another, and have many tables to join and many
    combinations
    Thanks

    Functions can be used in a select statement subject to certain
    restrictions, see
    http://otn.oracle.com/docs/products/oracle8i/doc_library/817_doc/
    server.817/a85397/statem9b.htm#2062024
    It's under "CREATE FUNCTION> Keywords and Parameters> function>
    Restrictions on User-Defined Functions"
    Here is an except...
    When a function is called from within a query or DML statement,
    the function cannot:
    a) Have OUT or IN OUT parameters
    b) Commit or roll back the current transaction, create or roll
    back to a savepoint, or alter the session or the system. DDL
    statements implicitly commit the current transaction, so a user-
    defined function cannot execute any DDL statements.
    c) Write to the database, if the function is being called from a
    SELECT statement. However, a function called from a subquery in
    a DML statement can write to the database.
    d) Write to the same table that is being modified by the
    statement from which the function is called, if the function is
    called from a DML statement.
    Except for the restriction on OUT and IN OUT parameters, Oracle
    enforces these restrictions not only for the function called
    directly from the SQL statement, but also for any functions that
    function calls, and on any functions called from the SQL
    statements executed by that function or any function it calls.

  • Re: Select statement fails under Express, but works underForte when usi

    Hi there,
    I have logged this with Forte and it as been recognized as a bug ( #46554 ).
    The Express methods you need to look at if you want to modify this behavior
    are :
    1 - BusinessQuery.BuildQuery() starting at line 217
    2 - SqlQuery.GetWhereText() starting at line 60
    We have gotten around the problem by modifying what Express generates by
    changing it from ( col1, col2 ) in ( select col1, col2 ... ) to ( col1 +
    col2 ) in ( select col1 + col2 ... )
    Just one thing i'm not sure that the '+' is standard on every DBMS for
    concatenation.
    We are using SQL Server 6.5
    Hope this helps.
    Christian Boult ([email protected])
    Programmeur - Analyste
    Influatec inc.
    -----Original Message-----
    From: Metcalf, Roger <[email protected]>
    To: '[email protected]' <[email protected]>
    Date: Thursday, May 06, 1999 1:55 PM
    Subject: Select statement fails under Express, but works under Forte when
    using DB2
    Express sometimes (e.g. with nested windows) generates SQL with a select
    subquery, e.g.
    select x1, x2 from t1 where (x1,x2) in (select x1,x2 from t2.....)
    This fails on DB2 with a message that the comma in the where clause (x1,x2)
    is not allowed.
    This works on Oracle.
    Does anyone have a workaround or other suggestion?
    To unsubscribe, email '[email protected]' with
    'unsubscribe forte-users' as the body of the message.
    Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/>
    To unsubscribe, email '[email protected]' with
    'unsubscribe forte-users' as the body of the message.
    Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/>

    joe.meszaros wrote:
    (SELECT ? AS Id, ? AS UserBytes FROM dual)I suggest that you test to see if that statement and ONLY that statement works at all.
    There are rules for bind variables and that statement certainly looks suspicious.
    If you can't get that to work then the rest of the attempt is pointless.

  • Re: Select statement fails under Express, but works underForte whenusin

    Roger,
    This was a bug with Express and was fixed in Express E.2.0.L.0.
    You might be able to get more details on Forte's website.
    Ajith Kallambella M
    From: "Metcalf, Roger" <[email protected]>
    Reply-To: "Metcalf, Roger" <[email protected]>
    To: "'[email protected]'" <[email protected]>
    Subject: Select statement fails under Express, but works under Forte
    whenusing DB2
    Date: Thu, 6 May 1999 11:55:19 -0400
    Express sometimes (e.g. with nested windows) generates SQL with a select
    subquery, e.g.
    select x1, x2 from t1 where (x1,x2) in (select x1,x2 from t2.....)
    This fails on DB2 with a message that the comma in the where clause (x1,x2)
    is not allowed.
    This works on Oracle.
    Does anyone have a workaround or other suggestion?
    To unsubscribe, email '[email protected]' with
    'unsubscribe forte-users' as the body of the message.
    Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/>_______________________________________________________________
    Get Free Email and Do More On The Web. Visit http://www.msn.com
    To unsubscribe, email '[email protected]' with
    'unsubscribe forte-users' as the body of the message.
    Searchable thread archive <URL:http://pinehurst.sageit.com/listarchive/>

    joe.meszaros wrote:
    (SELECT ? AS Id, ? AS UserBytes FROM dual)I suggest that you test to see if that statement and ONLY that statement works at all.
    There are rules for bind variables and that statement certainly looks suspicious.
    If you can't get that to work then the rest of the attempt is pointless.

  • If statement in select statement alias

    I have the following select statement. It has the alias Survivors, Deaths and "All Cases". Is it posible to use :P_LANGUAGE variable to say that -- IF :P_LANGUAGE = FRENCH THEN alias are Survivants for survivors, Décès for Deaths, Tous_les_cas for All Cases. Please advise
    SELECT ALL T_NTR_MULTIBAR.CAT, T_NTR_MULTIBAR.NUM_CASES_LEFTBAR AS Survivors,
    T_NTR_MULTIBAR.NUM_CASES_MIDDLEBAR AS Deaths, T_NTR_MULTIBAR.NUM_CASES_RIGHTBAR AS "All Cases"
    FROM T_NTR_MULTIBAR
    WHERE INSTANCE_NUM = :P_INSTANCENUM
    order by ORDERS

    You may not be able to add this condition inside the SQL Statement. But you can add this condition outside the statement, if you're using PL/SQL...
    IF :p_language = french THEN
    SELECT ALL t_ntr_multibar.cat,
      t_ntr_multibar.num_cases_leftbar AS survivors,
      t_ntr_multibar.num_cases_middlebar AS deaths,
      t_ntr_multibar.num_cases_rightbar AS "All Cases"
    ELSE
    END IF;

Maybe you are looking for