Subquery in the Select Clause

Can a subquery in the select clause return more than one field?
Something like this:
select ename,
(select dname, loc from dept where e.deptno = deptno) as (dname,loc)
from emp e

A simple way to find out is to test it. In my tests below, the original query produces an error that says it didn't find FROM where it expected. Eliminating "as (dname,loc)" produces an error about too many values. Putting only one value in the subquery in the select clause works, whether it is dname or loc. Concatenating the two columns as dname || ' ' || loc to produce one value in the subquery in the select clause works. Using two separate subqueries, one for dname and one for loc works. And, lastly, a cursor statement with both values works, although the output is a little hard to read. This may be different in newer versions. I am using Oracle 8.1.7. It may be different in 9i. I was unable to locate any documentation on the cursor statement or cursor operator which I have also heard it called. I only knew to try it because I have seen it used. I looked up the SELECT syntax in the 9i SQL Reference and there was no mention of cursor in the select clause. Can anyone provide a link to some documentation on this? I vaguely recall reading something that said that, other than outputting from SQL*Plus as below, it wasn't yet compatible with anything else, like you can't use it in PL/SQL, but I can't remember where I read it.
SQL> -- 2 values in subquery in select clause:
SQL> select ename,
  2  (select dname, loc from dept where e.deptno = deptno) as (dname,loc)
  3  from emp e
  4  /
(select dname, loc from dept where e.deptno = deptno) as (dname,loc)
ERROR at line 2:
ORA-00923: FROM keyword not found where expected
SQL> select ename,
  2  (select dname, loc from dept where e.deptno = deptno)
  3  from emp e
  4  /
(select dname, loc from dept where e.deptno = deptno)
ERROR at line 2:
ORA-00913: too many values
SQL> -- 1 value in subquery in select clause:
SQL> select ename,
  2  (select dname from dept where e.deptno = deptno)
  3  from emp e
  4  /
ENAME      (SELECTDNAMEFR                                                      
SMITH      RESEARCH                                                            
ALLEN      SALES                                                               
WARD       SALES                                                               
JONES      RESEARCH                                                            
MARTIN     SALES                                                               
BLAKE      SALES                                                               
CLARK      ACCOUNTING                                                          
SCOTT      RESEARCH                                                            
KING       ACCOUNTING                                                          
TURNER     SALES                                                               
ADAMS      RESEARCH                                                            
JAMES      SALES                                                               
FORD       RESEARCH                                                            
MILLER     ACCOUNTING                                                          
14 rows selected.
SQL> select ename,
  2  (select loc from dept where e.deptno = deptno)
  3  from emp e
  4  /
ENAME      (SELECTLOCFRO                                                       
SMITH      DALLAS                                                              
ALLEN      CHICAGO                                                             
WARD       CHICAGO                                                             
JONES      DALLAS                                                              
MARTIN     CHICAGO                                                             
BLAKE      CHICAGO                                                             
CLARK      NEW YORK                                                            
SCOTT      DALLAS                                                              
KING       NEW YORK                                                            
TURNER     CHICAGO                                                             
ADAMS      DALLAS                                                              
JAMES      CHICAGO                                                             
FORD       DALLAS                                                              
MILLER     NEW YORK                                                            
14 rows selected.
SQL> select ename,
  2  (select dname || ' ' || loc from dept where e.deptno = deptno)
  3  from emp e
  4  /
ENAME      (SELECTDNAME||''||LOCFROMDEP                                        
SMITH      RESEARCH DALLAS                                                     
ALLEN      SALES CHICAGO                                                       
WARD       SALES CHICAGO                                                       
JONES      RESEARCH DALLAS                                                     
MARTIN     SALES CHICAGO                                                       
BLAKE      SALES CHICAGO                                                       
CLARK      ACCOUNTING NEW YORK                                                 
SCOTT      RESEARCH DALLAS                                                     
KING       ACCOUNTING NEW YORK                                                 
TURNER     SALES CHICAGO                                                       
ADAMS      RESEARCH DALLAS                                                     
JAMES      SALES CHICAGO                                                       
FORD       RESEARCH DALLAS                                                     
MILLER     ACCOUNTING NEW YORK                                                 
14 rows selected.
SQL> select ename,
  2  (select dname from dept where e.deptno = deptno),
  3  (select loc from dept where e.deptno = deptno)
  4  from emp e
  5  /
ENAME      (SELECTDNAMEFR (SELECTLOCFRO                                        
SMITH      RESEARCH       DALLAS                                               
ALLEN      SALES          CHICAGO                                              
WARD       SALES          CHICAGO                                              
JONES      RESEARCH       DALLAS                                               
MARTIN     SALES          CHICAGO                                              
BLAKE      SALES          CHICAGO                                              
CLARK      ACCOUNTING     NEW YORK                                             
SCOTT      RESEARCH       DALLAS                                               
KING       ACCOUNTING     NEW YORK                                             
TURNER     SALES          CHICAGO                                              
ADAMS      RESEARCH       DALLAS                                               
JAMES      SALES          CHICAGO                                              
FORD       RESEARCH       DALLAS                                               
MILLER     ACCOUNTING     NEW YORK                                             
14 rows selected.
SQL> -- cursor statement:
SQL> select ename,
  2  cursor (select dname, loc from dept where e.deptno = deptno)
  3  from emp e
  4  /
ENAME      CURSOR(SELECTDNAME,L                                                
SMITH      CURSOR STATEMENT : 2                                                
CURSOR STATEMENT : 2
DNAME          LOC                                                             
RESEARCH       DALLAS                                                          
1 row selected.
ALLEN      CURSOR STATEMENT : 2                                                
CURSOR STATEMENT : 2
DNAME          LOC                                                             
SALES          CHICAGO                                                         
1 row selected.
WARD       CURSOR STATEMENT : 2                                                
CURSOR STATEMENT : 2
DNAME          LOC                                                             
SALES          CHICAGO                                                         
1 row selected.
JONES      CURSOR STATEMENT : 2                                                
CURSOR STATEMENT : 2
DNAME          LOC                                                             
RESEARCH       DALLAS                                                          
1 row selected.
MARTIN     CURSOR STATEMENT : 2                                                
CURSOR STATEMENT : 2
DNAME          LOC                                                             
SALES          CHICAGO                                                         
1 row selected.
BLAKE      CURSOR STATEMENT : 2                                                
CURSOR STATEMENT : 2
DNAME          LOC                                                             
SALES          CHICAGO                                                         
1 row selected.
CLARK      CURSOR STATEMENT : 2                                                
CURSOR STATEMENT : 2
DNAME          LOC                                                             
ACCOUNTING     NEW YORK                                                        
1 row selected.
SCOTT      CURSOR STATEMENT : 2                                                
CURSOR STATEMENT : 2
DNAME          LOC                                                             
RESEARCH       DALLAS                                                          
1 row selected.
KING       CURSOR STATEMENT : 2                                                
CURSOR STATEMENT : 2
DNAME          LOC                                                             
ACCOUNTING     NEW YORK                                                        
1 row selected.
TURNER     CURSOR STATEMENT : 2                                                
CURSOR STATEMENT : 2
DNAME          LOC                                                             
SALES          CHICAGO                                                         
1 row selected.
ADAMS      CURSOR STATEMENT : 2                                                
CURSOR STATEMENT : 2
DNAME          LOC                                                             
RESEARCH       DALLAS                                                          
1 row selected.
JAMES      CURSOR STATEMENT : 2                                                
CURSOR STATEMENT : 2
DNAME          LOC                                                             
SALES          CHICAGO                                                         
1 row selected.
FORD       CURSOR STATEMENT : 2                                                
CURSOR STATEMENT : 2
DNAME          LOC                                                             
RESEARCH       DALLAS                                                          
1 row selected.
MILLER     CURSOR STATEMENT : 2                                                
CURSOR STATEMENT : 2
DNAME          LOC                                                             
ACCOUNTING     NEW YORK                                                        
1 row selected.
14 rows selected.

Similar Messages

  • Subquery in the Where clause

    Can I put a subquery in the where clause, on the left side on the operator?
    This is a multi-row query.
    Like this,
       select a.col1, a.col2, b.col1, b.col2,
                 my_function(a.date1, b.date2) AS GROSSDAYS
       from table1 a
       where ( select ( a.date1 - b.date2 ) as range
                   from     table1 a
                   join      table2 b
                   on       a.col3 = b.col3
                   where rownum =1
                   in ( 1,2,3)
    and  a.col1 = b.col2I need to use a subquery because the column I need does not exist in the table, and I cannot make any changed to the table structure.
    Is what I'm doing possible?
    The subquery is the same as the function I have in the Select clause.

    I tried a subquery in the where clause, but now I'm getting a missing expression error!
       SELECT
            r.complete_flag, r.order_num, r.referral_num, TRUNC(r.referral_datetime) AS referral_datetime,
            r.clinic_specialty, a.appointment_datetime, TRUNC(a.appointment_date_made) AS appt_datemade, a.appointment_status_id,
             scref.scr_rules.calcatcdays(r.referral_datetime,a.appointment_date_made) AS ATCDays  -- returns difference between two dates
    FROM
            referral r,
                                 ( SELECT referral_num,appointment_datetime, appointment_date_made, appointment_status_id
                                      FROM   ( SELECT referral_num, appointment_datetime, appointment_date_made, appointment_status_id,
                                                ROW_NUMBER() OVER (PARTITION BY referral_num
                                                ORDER BY appointment_datetime) rn
                                            FROM   appointment
                                     WHERE rn = 1
                             a
    WHERE r.order_num IS NOT NULL
    AND   ( SELECT adays                      -- THIS IS WHERE I'M GETTING A MISSING EXPRESSION ERROR!!!
           FROM ( SELECT scref.scr_rules.calcatcdays(r.referral_datetime,a.appointment_date_made) AS adays
                    FROM referral r
                     JOIN appointment a
                     ON   a.referral_num = r.referral_num
                     WHERE ROWNUM = 1
           WHERE  adays
          ) = 3
    AND   r.referral_num = a.referral_num(+)
    AND   TRUNC(r.referral_datetime) >= TO_DATE('01-JUL-05','DD-MON-YY')
    AND   TRUNC(r.referral_datetime) <= TO_DATE('31-JUL-05','DD-MON-YY')

  • Subquery in the From Clause

    I have a query the contains a subquery in the from clause. The problem is how to join one of the tables in the subquery to one of the main tables. If I hard a value, the query runs, but using a table.column produced an "invalid column name" error.
    Examples of both are below.
    This one works
    SELECT a.pay_rate, a.bill_rate, a.frequency, c.value
    FROM SYSADM.ps_pb_wkord_sq_rte a, SYSADM.ps_md_erncd_action b,
    SELECT DISTINCT z.value
    FROM SYSADM.ps_md_erncd_action z
    WHERE z.md_action = 'CALC_BURD' AND
    z.system_id = 'PB' AND
    z.erncd = 'REG' AND **This is the line in question**
    z.effdt = (
    SELECT MAX(z_ed.effdt)
    FROM SYSADM.ps_md_erncd_action z_ed
    WHERE z.setid = z_ed.setid AND
    z.erncd = z_ed.erncd AND
    z.effdt = z_ed.effdt AND
    z.system_id = z_ed.system_id AND
    z.md_action = z_ed.md_action AND
    z_ed.effdt <= TO_DATE('04/01/2001','MM/DD/YYYY'))) c
    WHERE a.erncd = b.erncd AND
    b.effdt = (
    SELECT MAX(b_ed.effdt)
    FROM SYSADM.ps_md_erncd_action b_ed
    WHERE b.setid = b_ed.setid AND
    b.erncd = b_ed.erncd AND
    b.effdt = b_ed.effdt AND
    b.system_id = b_ed.system_id AND
    b.md_action = b_ed.md_action AND
    b_ed.effdt <= TO_DATE('04/01/2001','MM/DD/YYYY')) AND
    a.group_id = 'PSD01' AND
    a.workorder_no = 'H00034758' AND
    a.assignment_no = 'H00034758-001' AND
    b.system_id = 'PB' AND
    b.md_action = 'EARN_TYPE' AND
    b.value = 'R';
    This one produces the error
    SELECT a.pay_rate, a.bill_rate, a.frequency, c.value
    FROM SYSADM.ps_pb_wkord_sq_rte a, SYSADM.ps_md_erncd_action b,
    SELECT DISTINCT z.value
    FROM SYSADM.ps_md_erncd_action z
    WHERE z.md_action = 'CALC_BURD' AND
    z.system_id = 'PB' AND
    z.erncd = a.erncd AND **This is line in question**
    z.effdt = (
    SELECT MAX(z_ed.effdt)
    FROM SYSADM.ps_md_erncd_action z_ed
    WHERE z.setid = z_ed.setid AND
    z.erncd = z_ed.erncd AND
    z.effdt = z_ed.effdt AND
    z.system_id = z_ed.system_id AND
    z.md_action = z_ed.md_action AND
    z_ed.effdt <= TO_DATE('04/01/2001','MM/DD/YYYY'))) c
    WHERE a.erncd = b.erncd AND
    b.effdt = (
    SELECT MAX(b_ed.effdt)
    FROM SYSADM.ps_md_erncd_action b_ed
    WHERE b.setid = b_ed.setid AND
    b.erncd = b_ed.erncd AND
    b.effdt = b_ed.effdt AND
    b.system_id = b_ed.system_id AND
    b.md_action = b_ed.md_action AND
    b_ed.effdt <= TO_DATE('04/01/2001','MM/DD/YYYY')) AND
    a.group_id = 'PSD01' AND
    a.workorder_no = 'H00034758' AND
    a.assignment_no = 'H00034758-001' AND
    b.system_id = 'PB' AND
    b.md_action = 'EARN_TYPE' AND
    b.value = 'R';
    Any help is greatly appreciated.
    Thanks,
    JD Lippard

    Hi JD,
    your code is very difficult to read to i will give you some general information.
    SELECT t1.c1,t1.c2
    FROM table t1
    , (SELECT t2.col1 alias1
    , t2.col2 alias2
    , a.s.o.
    FROM anytable t2
    ) tablealias
    WHERE t1.c1 = tablealias.alias1
    You can select any columns inside this 'dynamic view' whichever you need for a join. Independent if you print them or not.
    But you cannot join INSIDE this dynamic view to outer tables like
    SELECT t1.c1,t1.c2
    FROM table t1
    , (SELECT t2.col1 alias1
    , t2.col2 alias2
    , a.s.o.
    FROM anytable t2
    WHERE t1.c2 = t2.col2
    ) tablealias
    WHERE bla
    Maybe it helps a bit.
    Cheers,
    Udo

  • Merge can't accept a variable in the select clause?

    oracle 10.2
    I have a stored procedure.
    I have a variable, vseq, which I set a sequence variable. With all other sql statements I can do
    insert into table a
    select vseq
    from dual;
    Apparently a merge can't handle variables in the select clause. I get an error. I can get it to work when I hard code a value.
    this is ridiculous...

    merge can't handle variables in the select clauseCare to prove?
    sql> DECLARE
      2   v_first_name varchar2(20) := 'BOSS';
      3  BEGIN
      4  MERGE INTO sun_employees se
      5  USING (SELECT * FROM employees WHERE department_id = 20) e
      6  ON (e.employee_id = se.employee_id)
      7  WHEN MATCHED THEN
      8    UPDATE SET salary = e.salary
      9  WHEN NOT MATCHED THEN
    10  INSERT(employee_id, first_name, last_name, department_id)
    11  VALUES (e.employee_id, v_first_name, e.last_name, e.department_id);
    12  END;
    13  /
    PL/SQL procedure successfully completed.
    sql> select first_name from sun_employees;
    FIRST_NAME
    BOSS
    BOSS

  • Using @Prompt in the SELECT clause (?)

    Post Author: faltinowski
    CA Forum: Semantic Layer and Data Connectivity
    Product:  Business Objects
    Version:  6.5 SP3 
    Patches Applied:  MHF11 and CHF48
    Operating System(s):  Windows
    Database(s):  Oracle
    Error Messages:  "Parse failed: Exception: DBD, ORA-00903 invalid table name  State N/A"
    Hi!  I'm bewildered -- we have an object that parses but when I try to reproduce this object, it does not.
    We have a universe that's been in production for several years using an object developed by another designer who's no longer with the company.  This object is a dimension, datatype is character, and there's no LOV associated.  The SELECT statement in this object is
    decode(@Prompt('Select Snapshot Month','A','Object Definitions\CY Month Snapshot',MONO,CONSTRAINED),'00-Previous Month',to_number(to_char(add_months(sysdate,-1),'MM')),'01-Current Month',to_number(to_char(add_months(sysdate,0),'MM')),'01-January','1','02-February','2','03-March','3','04-April','4','05-May','5','06-June','6','07-July','7','08-August','8','09-September','9','10-October','10','11-November','11','12-December','12')
    This object parses. The client uses the object in the select clause to capture the "month of interest" for the report.  So the report may be for the entire year's data which is graphed to show trends, but there's a table below the graph which is filtered to show just the month of interest.  Typically they use the value "00-Previous Month" so they can schedule the report and it will always show the last month's data.
    Problem
    The original object parses.
    If I copy the object within the same universe, it parses.
    If I copy the code into a new object in the same universe, it doesn't parse
    If I copy the code into a new object in a different universe, it doesn't parse
    If I copy the object to a different universe, then edit the LOV reference, it doesn't parse
    If I create any new object having @Prompt in the SELECT statement, it doesn't parse.
    If another designer tries - they get the same thing.
    What am I missing?  Obviously someone was able to create this successfully.
    On the brighter side
    The object I created in a new universe (which doesn't parse in the universe) seems to work fine in the report.

    Seems that, the prompt syntax is correct.
    But the condition is not correct.
    You are taking the prompt value and not doing anything. That could be one issue for this error.
    I believe that, you just want to capture the prompt value use it in report level and do not want to apply as a filter.
    So, use the condition as follows.
    @Prompt('Select Grouping','A',{'A','B','C'},mono,constrained) = @Prompt('Select Grouping','A',{'A','B','C'},mono,constrained)
    Hope this helps!

  • Problems with query with more than 20 values in the select clause

    I have a region based on a function returning a SQL query. It needs to have more than 20 values in the select clause. When I run the page I get a no data found error in the region. I managed to reproduce this behavior with just the following as the select returned by the function:
    select 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21
    from dual
    I am running the 1.3.9.00.15 release of Marvel on 9.2.0.2 of the db on Solaris.

    Hello Raju,
    I will email you the connection settings when I return to the office.
    One thing I should have mentioned: The sql string is returned from a package in the db, so the query region text I originally posted isn't quite correct.
    it is something like:
    declare
    begin
    return my_pkg.my_fnc;
    end;
    the stored package is nothing more than:
    package my_pks is
    funtion my_fnc(i_test_param in varchar2) is
    begin
    return 'select 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20, 21 from dual';
    end;
    end;
    Sorry for the inaccurate info in the first post, but I am away from the server in question right now.

  • In a SQL statement, the SELECT clause is used to

    In a SQL statement, the SELECT clause is used to select
    (a) columns
    (b) rows
    (c) tables
    (d) none of the above
    can any one help Immediately

    Is used to select rows of specified column...
    SELECT column_name(s) FROM table_name

  • Subquery in the HAVING Clause

    Hello all,
    i'm getting error when i try to write sub query in having clause. check out my query
    select  ROUND( Count( distinct  Sales2011_DIVDPTA.DIVDPTA_Item_Dept ),0)  AS  "F1" , ROUND( Count( Sales2011.Sales2011_DG1.Item_Season ),0)  AS  "F2"  
    from Sales2011.Sales2011_JT    
      INNER JOIN Sales2011.Sales2011_DG1 On Sales2011.Sales2011_DG1.DG1_ID =Sales2011.Sales2011_JT.DG1_ID   
    LEFT JOIN Sales2011.Sales2011_DIVDPTA On nvl(Sales2011.Sales2011_DIVDPTA.DIVDPTA_ITEM_DIVISION,' ')=nvl(Sales2011.Sales2011_DG1.Item_Division,' ')
      AND  nvl(Sales2011.Sales2011_DIVDPTA.DIVDPTA_ITEM_DEPT,' ')=nvl(Sales2011.Sales2011_DG1.Item_Dept,' ')       
    having ( ROUND( Count( Sales2011.Sales2011_DG1.Item_Season ),0)     in ( 0)
    But it is not executed if I use the sub query in having clause
    select  ROUND( Count( distinct  Sales2011_DIVDPTA.DIVDPTA_Item_Dept ),0)  AS  "F1" ,  ROUND( Count( Sales2011.Sales2011_DG1.Item_Season ),0)  AS  "F2"   
    from Sales2011.Sales2011_JT       
    INNER JOIN Sales2011.Sales2011_DG1 On Sales2011.Sales2011_DG1.DG1_ID =Sales2011.Sales2011_JT.DG1_ID   
    LEFT JOIN Sales2011.Sales2011_DIVDPTA On nvl(Sales2011.Sales2011_DIVDPTA.DIVDPTA_ITEM_DIVISION,' ')=nvl(Sales2011.Sales2011_DG1.Item_Division,' ')
    AND  nvl(Sales2011.Sales2011_DIVDPTA.DIVDPTA_ITEM_DEPT,' ')=nvl(Sales2011.Sales2011_DG1.Item_Dept,' ')        
    having ( ROUND( Count( Sales2011.Sales2011_DG1.Item_Season ),0)
    in ( select   ROUND( Count(
    Sales2011.Sales2011_DG1.Item_Season ),0)  from    Sales2011.Sales2011_DG1 )
    Error at Command Line:1 Column:0
    Error report:
    SQL Error: ORA-00979: not a GROUP BY expression
    00979. 00000 -  "not a GROUP BY expression"
    *Cause:   
    *Action:any help ???

    Sorry unintentionally i have posted my question here.
    will you please elaborate this? Becoz i'm not using group by clause in both query. First query run successfully but as i put sub query in having clause it raised an error. will you tell where i'm committing mistake?
    Aggregates in the HAVING clause do not need to appear in the SELECT list. If the HAVING clause contains a subquery, the subquery can refer to the outer query block if and only if it refers to a grouping column.Edited by: Oracle Studnet on Aug 14, 2011 11:28 PM

  • Calling a function in the select clause.

    I am using Oracle 11g.
    I am trying to write a query like this
    select name,age, sal, avg = avg_salary(age)
    from customer
    where sal >= avg;
    However, I am not able to do so. What the query is trying to do is print the name, age and salary of every customer as well as the average salary for the customer's age where the customer's salary is greater than the average salary for his age.
    Please help. Thanks.

    Hi,
    The way to assign a column alias is to put the alais after the expression. It makes your code clearer if you put the keyword AS after the expression and before the alias, but this is not required.
    SELECT     name
    ,     age
    ,     sal
    ,     avg_salary (age)     AS avg_salary_age
    FROM     customer
    WHERE     sal     >= avg_salary (age)
    ;You can't reference a column alais in the same query where it is defined (except in an ORDER BY clause). If you want to reference the alias anywhere else (e.g., in the WHERE clause) you have to define it in a sub-query; then you can use it anywhere you want in the super-query, liek this:
    WITH     got_avg_salary_age     AS
         SELECT     name
         ,     age
         ,     sal
         ,     avg_salary (age)     AS avg_salary_age
         FROM     customer
    SELECT     *
    FROM     got_avg_salary_age
    WHERE     sal     >= avg_salary_age
    ;Since AVG is the name of a built-in function, there could be problems using it as a column alias. You could call it average, if you don't like avg_salary_age.

  • Dividing the SELECT clause to understand

    Hi All,
    I am given a code which has very complicated SELECT clause which I am not able to break in understandable form.
    Its like this:
    for i in (select 'select ROWIDTOCHAR(rowid) rid, studyid, '''||db_link||''' db_link, rowid || '':'' || studyid || '':'' || '''||db_link||''' as text from consolidated.cp_queue_tbl'||decode(db_link,null,null,'@'|| db_link|| ' where process_start_time is null') stat from (select distinct db_link from cp_study_metadata_tbl))
    I am not able to understand which are actual column and which are aliases among this. Neither I can understand where oen query ends and other begins.
    Please help
    Aashish S.

    Are you sure that the parenthesis that stands immediatly before "stat" is well placed?
    You're adding the where clause only if selecting through database link, seems strange...
    Maybe it should be
    FOR i IN
    (SELECT 'select ROWIDTOCHAR(rowid) rid, studyid, '''||
             db_link||''' db_link, rowid || '':'' || studyid || '':'' || '''||
             db_link||''' as text from consolidated.cp_queue_tbl'||
             DECODE(db_link,null,null,'@'||db_link)||' where process_start_time is null' stat
    FROM (SELECT DISTINCT db_link
           FROM cp_study_metadata_tbl)
    )Max
    [My Italian Oracle blog|http://oracleitalia.wordpress.com/2009/12/29/estrarre-i-dati-in-formato-xml-da-sql/]

  • Date comparison in the select clause

    I want to have comparison as if date1 >= date2 then select as 1 or select as 2. This should be in the select clause

    select greatest (date1, date2)
    from table
    ~
    pascal

  • How to overwrite an inner query in the select clause

    Hello,
    I have a queryof this form:
    SELECT t1.ID,
               t1.column2,
               (SELECT SUM (t2.column2)
                    FROM table2 t2
                  WHERE t2 = t.ID
                       AND t2.column1 IN (SELECT ..... FROM table3 t3 WHERE t3.column1 = t1.column3 ........)
        FROM table1 t1At the stage where I select from table3 I do not see the columns of table1. In other words:
      t3.column1 = t1.column3will NOT work.
    The version of the database is 10.2.0.4.
    How could I rewrite this piece of code in order to surround the problem?
    I cannot join table3 with table1 in the outermost query, because the structure of this database is such that it would not work for me.
    I know that most of you would say, change the DB structure, but anyway, any ideas? :)
    Besides, is the same restriction for inner queries applicable in Oracle 11g2?
    Thanks

    user13080027 wrote:
    Hi
    I mean I receive the error ORA-00904-"t1.column3" invalid identifier.Something does not add up here. You said earlier
    I cannot join table3 with table1 in the outermost query, because the structure of this database is such that it would not work for me.Why can't you rewrite your query something like follows:
    SELECT t1.ID,
               t1.column2,
               (SELECT SUM (t2.column2)
                    FROM table2 t2
                  WHERE t2 = t.ID
                       AND t2.column1 = t3.column3
        FROM table1 t1, table3 t3
    WHERE t3.column1 = t1.column3p.s. I am not saying this is the exact query you need but then you don't provide any details requested. ;)

  • Getting Exception in the select clause - Very Urgent

    Hi,
        I have given the below statement but it is showing the exception.
      SELECT *
             FROM (lv_tab_name)
             INTO CORRESPONDING FIELDS OF TABLE <fs_1>.
    If I execute the above select statement it is showing the below exception.
    Exception CX_SY_NO_HANDLER triggered.
    An exception with the type CX_SY_OPEN_SQL_DB occurred.
    It is working very well if I mention the few field names.
    Please let me know the possible reasons.
    Thanks,
    Suvin

    Thanks much for your quick response.
    I have tried with what you mentioned but it is not working.
    Please find my code below.
    *Declarations
    DATA: ddfields TYPE STANDARD TABLE OF ddfield.
      DATA: ls_ddfields TYPE ddfield.
      DATA: lt TYPE lvc_t_fcat.
      DATA: ls TYPE lvc_s_fcat.
      DATA: lv_tab_name TYPE dd02l-tabname.
    Data References
      DATA: lt_data TYPE REF TO data.
      DATA: new_line TYPE REF TO data.
    Field Symbols
      FIELD-SYMBOLS: <fs_1> TYPE ANY TABLE.
      FIELD-SYMBOLS: <fs_data> TYPE REF TO data.
      FIELD-SYMBOLS: <fs_2> TYPE ANY,
                     <l_field> TYPE ANY.
    Get the fields of the database table, here i am passing the table name
      CALL FUNCTION 'DD_NAMETAB_TO_DDFIELDS'
        EXPORTING
      KEYFIELDS       = 'X'
      NULLABLE        = 'X'
            tabname        = lv_tab_name
        TABLES
            ddfields        = ddfields.
      LOOP AT ddfields INTO ls_ddfields.
        ls-fieldname = ls_ddfields-fieldname.
        APPEND ls TO lt.
      ENDLOOP.
    *Assigning Field-Symbol to our dynamic internal table
      ASSIGN lt_data TO <fs_data>.
    Calling the method CREATE_DYNAMIC_TABLE
      CALL METHOD cl_alv_table_create=>create_dynamic_table
        EXPORTING
          it_fieldcatalog           = lt
        IMPORTING
          ep_table                  = <fs_data>
        EXCEPTIONS
          generate_subpool_dir_full = 1
          OTHERS                    = 2.
      IF sy-subrc EQ 0.
        ASSIGN <fs_data>->* TO <fs_1>.
    Create a work area for the dynamic table.
        CREATE DATA new_line LIKE LINE OF <fs_1>.
    A field-symbol to access that work area
        ASSIGN new_line->*  TO <fs_2>.
      ENDIF.
    Selecting the Data from the respective table.
      SELECT *
             FROM (lv_tab_name)
             INTO CORRESPONDING FIELDS OF TABLE <fs_1>.
    Please advise..it is very urgent.
    Thanks,
    Suvin

  • Using if logic in the where clause of a select statement

    I have a select clause. And in the select clause there is a variable all_off_trt that can be 'Y' or 'N'.
    In the where clause I want to make it so that if a form variable is checked and all_off_trt is 'Y' then
    exclude it else if the form variable isn't checked then select it no matter what all_off_trt is.
    Is there any way to include either and if statement or a case statement within the where clause to acheive this? If not is there another way of doing it?
    Basically I am looking for a case statement like this
    case
    when all_off_trt = 'Y' and mail_para.code = 'Y' then false
    else true
    end
    Message was edited by:
    Tugnutt7

    Ok, so that really doesn't solve my problem. I have 3 different fields that I need to do that with. Each combining in a select statement to print an email list, as well as other thing limiting the where clause.
    This is currently what I have, tested and working 100%.
    cursor email_cur is
         select unique p.email,s.all_off_trt,s.all_deceased,s.no_enroll
    from participant p, trialcom t, ethics s
    where p.status='A'
    and p.surname=t.surname
    and p.initials=t.initials
    and s.trial_cd = t.tricom
    and s.centre = t.centre
    and p.email is not null
    and (t.centre in (select code from mail_parameters where user_name=user and mail_para='CENTRE')
    or 'XX' in (select code from mail_parameters where user_name=user and mail_para='CENTRE'))
    and (t.tricom in (select code from mail_parameters where user_name=user and mail_para='TRIAL')
    or 'XX' in (select code from mail_parameters where user_name=user and mail_para='TRIAL'))
    and (t.role in (select code from mail_parameters where user_name=user and mail_para='ROLE')
    or 'XX' in (select code from mail_parameters where user_name=user and mail_para='ROLE'))
    and (p.country in (select code from mail_parameters where user_name=user and mail_para='COUNTRY')
    or 'XX' in (select code from mail_parameters where user_name=user and mail_para='COUNTRY'))
    and (t.represent in (select code from mail_parameters where user_name=user and mail_para='REPRESENT')
    or 'XX' in (select code from mail_parameters where user_name=user and mail_para='REPRESENT'));
    This is in a program unit that runs when a button is clicked. At the end of that I need to add on the 3 case statements that help further narrow down the selection of emails to be printed. Then it prints the emails selected from this statement into a file. So it has to be done right in the select statement. The three table variables are the all_off_trt, all_deceased, and no_enroll. The form has 3 checkboxes. One for each, that when checked (giving the variable associated with the checkboxes a value of 'Y') excludes all emails that have a 'Y' in the coresponding table variable.

  • Subquery in GROUP BY CLAUSE

    Is it possible to place a subquery in the GROUP BY CLAUSE? If it is, can anyone show me an example? thanks

    Hi,
    Here's a GROUP BY clause that uses an IN-subquery:
    SELECT    COUNT (*)     AS cnt
    FROM       scott.emp
    GROUP BY  CASE
              WHEN deptno  IN (
                             SELECT     deptno
                             FROM     scott.dept
                             WHERE     loc     = 'NEW YORK'
              THEN  1
              ELSE  2
           END
    ;I've never seen a need for this (and I've been to a state fair, a rodeo and a picnic!)
    Interestingly, if I copy the expression from the GROUP BY clause to the SELECT clause:
    SELECT    COUNT (*)     AS cnt
    ,       CASE
              WHEN deptno  IN (
                             SELECT     deptno
                             FROM     scott.dept
                             WHERE     loc     = 'NEW YORK'
              THEN  1
              ELSE  2
           END          AS new_york
    FROM       scott.emp
    GROUP BY  CASE
              WHEN deptno  IN (
                             SELECT     deptno
                             FROM     scott.dept
                             WHERE     loc     = 'NEW YORK'
              THEN  1
              ELSE  2
           END
    ;I get this error:
    ...             WHEN deptno  IN (
    ERROR at line 3:
    ORA-00979: not a GROUP BY expressionDespite what that book says, you can use an IN-subquery like this in an ORDER BY clause:
    SELECT       deptno
    FROM       scott.emp
    ORDER BY  CASE
              WHEN deptno  IN (
                             SELECT     deptno
                             FROM     scott.dept
                             WHERE     loc     = 'DALLAS'
              THEN  1
              ELSE  2
           END
    ;(New York is department 10, the first department anyway, so it's not as clear to use the exact same example.)

Maybe you are looking for

  • OSX Won't Start Up

    Hello, I've upgraded my Mabcook Pro to Mac OSX Mavericks several weeks ago, it works perfectly without any issue. Recently, I booted my mac onto OSX just fine, after I finish my work, I shut it down The next day, I tried to boot onto OSX, and there's

  • Report triggers

    Hello, I would like to create a trigger on "before report" to create several views. I have tried putting in some create view code into the pl/sql editor but keep getting errors. Can somebody give me a quick example of what the code should look like w

  • Skype WiFi for Windows Phone 8

    Hi, Anybody know if there is any Skype WiFi app for Windows Phone 7.8/8?

  • Home button response after 8 sec after IOS5. so is it hardware or software issue ?

    Please help. My ipone 4 is just out of warranty. was working fine with 4.33. once upgraded to ios 5 . it slowed to 4-5 secs. I did a reset and restore it becomes worse. Now phone is alomost useless , kind of disappointing coming from an expensive app

  • IC_EMAIL not working

    Hi, I am working 7.0. This query is regarding IC_EMAIL logical link. We are going to use standard workcenter, logical link IC_EMAIL in our interaction center. My requirement is after creation of enquiry some times user may create Email with reference