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 !

Similar Messages

  • Using procedure in SELECT statement

    I have a select statement that currently uses 4 functions to receive necessary values. All the functions are recursive and returns values from the same row.
    What I would like to do is replace these for function calls with 1 procedure. Does anybody know if it possible to use a procedure in this way inside a select statement?
    If so, do you have the syntax for doing this?
    E.g
    SELECT
    Mdbrd_Pkg.calculate_fixed_charge_fn(in_rc_id, ap.CONFIGSET_ID) AS FIXED_CHARGE,
    Mdbrd_Pkg.calculate_charge_rate_fn(in_rc_id, ap.CONFIGSET_ID) AS CHARGE_RATE,
    Mdbrd_Pkg.tax_liable_fn(in_rc_id, ap.CONFIGSET_ID) AS TAX_LIABLE,
    Mdbrd_Pkg.charge_unit_fn( in_rc_id, ap.CONFIGSET_ID) AS CHARGEUNIT_ID
    FROM .....

    This cannot be done. The part of the function used in the SELECT statement is the return value: procedures don't have return values (that's what makes tham procedures and not functions).
    Obviously I don't know what your code does, but you should consider putting them into a single function that returns a TYPE with four attributes and then using the TABLE() function to cast them into something you could reference in the FROM clause of a correlated sub-query. Sounds a bit messy though.
    Do these functions actually select data? Where does the recursion fit in?
    Cheers, APC

  • Why I Can't use procedure in select statement

    Why I Can't use procedure in select statement

    We can use function in select statement but we couldn't use procedure with one out parameters in select statement... You can use Function because they are designed for this but procedure are not. Functions can return value (without OUT parameter) which can be used in SELECT whereas procedures do not have such concept. As you can see in the above post you can not call even functions also if it has any out parameter.
    I have just trying to use procedure in select statement ..for this I require technical answer..The technical answer is because conceptually procedure is for doing set of operation, performning DMLs on the tables , whereas functions are for processing and producing a single result. Functions are basically for not using INSERT/UPDATE/DELETE in it. That is the reason they are allowed to be used in SELECT because conceptually they are not supposed to do any data changes.
    Regards,
    Avinash

  • Using Subquery in Prepared Statement

    can i use subquery in my insert using prepared statement
    need to specify the * property
    eg: insert into table1 values(select * from table2)

    can i use subquery in my insert using prepared
    statement
    need to specify the * property
    eg: insert into table1 values(select * from table2)Subqueries are perfectly okay, of course, but I think the proper idiom is:
    INSERT INTO foo(a, b, c)
    SELECT x, y, z
    FROM bar
    WHERE  x = 'baz'MOD

  • 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

  • Using Cursor in Select statements? How to do this?

    I am getting an error whilt passing a cursor to a select clause:
    SELECT dbms_xmlquery.getXML('select deptno, dname, '||
    'cursor(select empno, ename, sal from emp e where e.deptno = d.deptno) employees '||
    'from dept d where d.deptno in (10, 20)')
    FROM dual;
    DBMS_XMLQUERY.GETXML('SELECTDEPTNO'||'CURSORIS(SELECTEMPNOFROMEMPEWHEREE.DEPT=D.
    <?xml version = '1.0'?>
    <ERROR>oracle.xml.sql.OracleXMLSQLException: ORA-00923
    : FROM keyword not found where expected
    </ERROR
    THIS IS DUE TO THE CURSOR AND ITS FROM STATEMENT?
    CAN ANY ONE PLEASE GUIDE AS TO HOW TO USE CURSORS IN A SELECT STATEMENT PLEASE?

    Another duplicate thread. See my response Select CLAUSE error using CURSORS & XSU.Please SEE..
    Cheers, APC

  • Using variable in select statement (php)

    I am having difficulty using a variable in a select
    statement.
    The following manual query (using a static date) works fine:
    $query_Recordset1 = "SELECT * FROM academyClasses WHERE
    classDate > '2006-06-01' ";
    However, If I use the following:
    $dateVar = date('Y-m-d');
    mysql_select_db($database_mw, $mw);
    $query_Recordset1 = "SELECT * FROM academyClasses WHERE
    classDate > $dateVar ";
    ALL records are returned, which means the $dateVar variable
    is not being recognized. I have compared the $dateVar values
    <?php echo $datetime; ?> against the actual value of my date
    field <?php echo $row_Recordset1['classDate']; ?> in my
    results table and it seems that the values are indeed accurate in
    terms of a date 2006-06-04 for example.
    My date field "classDate" is of a "date" type within the
    mysql database. I'm using Dreamweaver MX 2004 with Mac OSX 10.3.9.
    I'm sure this is just a syntax problem, at least I hope it
    is.
    Any help is greatly appreciated.

    On Wed, 7 Jun 2006 04:49:57 +0000 (UTC), "mgwaters"
    <[email protected]> wrote:
    >Thanks Gary. That did seem to get the select statement
    working, but I had to
    >enter a manual date as before $dateVar = '2006-06-01'; on
    the previous line of
    >code to actually get it to filter my records. So... it
    looks like my setting of
    >the date variable:
    > $dateVar = date('Y-m-d');
    > does not seem to be recognized within the SELECT
    statement.
    Try this:
    $query_Recordset1 = "SELECT * FROM academyClasses WHERE
    classDate>'$dateVar'";
    print $query_Recordset1;
    See what is in the SQL statement.
    Gary

  • Using function in select statement

    Hi,
    CREATE FUNCTION [dbo].[udf_testFunction] 
    @value int
    RETURNS int
    AS
    BEGIN
    -- Declare the return variable here
    declare @returnValue int
    set @returnValue = @value*2;
    return @returnValue;
    END
    GO
    create table #Temp
        EmpID int, 
        EmpName Varchar(50)
    insert into #Temp(EmpID,EmpName) values(1,'Name1');
    insert into #Temp(EmpID,EmpName) values(2,'Name2');
    insert into #Temp(EmpID,EmpName) values(3,'Name3');
    insert into #Temp(EmpID,EmpName) values(4,'Name4');
    insert into #Temp(EmpID,EmpName) values(5,'Name5');
    select EmpID,EmpName, [dbo].[udf_testFunction](EmpID), [dbo].[udf_testFunction](EmpID)*EmpID,[dbo].[udf_testFunction](EmpID)+2 from #Temp
    In the above select statement i used [dbo].[udf_testFunction]() function 3 times. But i want to use only once and reuse it.
    Something like 
    select EmpID,EmpName, testfunctionvalue,testfunctionvalue*EmpID,testfunctionvalue+2 from #Temp
    Please advise me.... Thanks in Advance...

    You can use this code: 
    WITH cte
    AS ( SELECT EmpID ,
    EmpName ,
    [dbo].[udf_testFunction](EmpID) AS testfunctionvalue
    FROM #Temp
    SELECT EmpID ,
    EmpName ,
    testfunctionvalue ,
    testfunctionvalue * EmpID ,
    testfunctionvalue + 2
    FROM cte
    But using scalar functions in select clause can hurt the performance. Please see this link: 
    SQL Server Scalar User Defined Function Performance
    T-SQL Articles
    T-SQL e-book by TechNet Wiki Community
    T-SQL blog

  • Using TMVL in Select Statement

    Dear All,
    Is the usage of TMVL in Select Statement valid?
    *SELECT(%VAR_YEAR%, YEAR, TIME, ID = TMVL(-12, %TIME_SET%))
    I don't think I manage to get this statement running.
    Thanks,
    YL

    Thanks All.
    My requirement is:
    Copy from Source to Destination using script logic:
    Package Selections:
    Category : Forecast
    Time : 2025.12
    Version : 2025
    Source
    Dimension Category : Plan
    Dimension Time : 2025.12
    Dimension Version : 2024
    Destination
    Dimension Category : Forecast
    Dimension Time : 2025.12
    Dimension Version : 2025
    And question is how to derive Version 2024 which is 2025 - 1, without using a specific property for it, i.e. Previous Year?
    Thank you very much.
    Best regards,
    Yen Li

  • Want to use Index in Select statement

    Hi,
    I want to use the index tha is created for LIPS table for creation date. I want to use that INdex in the select statement to get the data from that table. Any one can tell me how can I right the select statement in report?
    thanks.

    Like I mentioned earlier, the optimizer is smart enough to choose the correct index based on the WHERE clause.  So if you created an index on field ERDAT for LIPS and your SELECT statement is like so.....
    Select ERDAT WERKS MATNR
              from LIPS
                          into table Itab
                                    Where erdat in s_erdat        "< - ERDAT First in WHERE Clause
                                        and werks in s_werks
                                        and Matnr in s_matnr.
    Then the optimizer will choose your index to use to access the data.  You can see these if you would do an SQL trace over your program and use the "Explain" button on ST05.  It will tell you which index it used and why.
    There is no need to use HINTs to force the use of the index.
    Regards,
    Rich Heilman

  • Is it better to use bapi_salesorder_getlist than select statements?

    hi experts,
    in terms of performance, which is better in getting a list of salesorders is it better bapi_salesorder_getlist or select statements?
    for bapi_salesorder_getlist, i will not get all of the fields so i would still use select.
    Message was edited by:
            maui bayog

    Hi,
    If ur requiremetn is specific and can be solved using bapi_salesorder_getlist then only use it, otherwise, use select stament which is more useful for reports as it gives o/p as required and not a predefined limited output.  Now u may get sufficient fields but , in future if requirement will change then for small change u may be in problem.
    Bapis are very userful for specifc and limited tasks.
    Jogdand M B

  • Using functions in select statement(joining 5 tables) taking long time in Oracle

    Hi,
    I have created a query in oracle which joins 5 tables and uses two functions(function names are 'ca_concat' and 'ca_concat_noseq').
    Query takes approximately 40 secs to execute around 12000 records. If I remove the functions from query it excutes within a second..
    Note : I have used the oracle SQL Developer for testing the query.
    It would be appriciated if anybody helps me to improve the perfomance of the query.
    Below are the querie with and without functions:
    1. Query with functions:
    select
    imsAuditEvent12.id as ID,
    imsAuditEvent12.audit_time as AUDIT_TIME,
    imsAuditEvent12.admin_dn as ADMIN_DN,
    imsAuditEvent12.admin_name as ADMIN_NAME,
    imsAuditEvent12.event_name as EVENT_NAME,
    imsAuditEvent12.event_description as EVENT_DESCRIPTION,
    imsAuditEvent12.event_state as EVENT_STATE,
    imsAuditEvent12.envname as ENVNAME,
    imsAuditTaskSession12.task_name as TASK_NAME,
    imsAuditTaskSession12.id as TASK_ID,
    imsAuditTaskSession12.task_description as TASK_DESCRIPTION,
    imsAuditTaskSession12.task_priority as TASK_PRIORITY,
    S1.OBJECT_ID,
    S1.OBJECT_NAME as OBJECT_NAME,
    S1.OBJECT_TYPE as OBJECT_TYPE,
    S2.ATTRIBUTE_NAME as ATTRIBUTE_NAME,
    S2.ATTRIBUTE_OLDVALUES as ATTRIBUTE_OLDVALUES,
    S2.ATTRIBUTE_NEWVALUES as ATTRIBUTE_NEWVALUES,
    S3.OBJECT_DN as OBJECT_DN,
    S3.OBJECT_TYPE as IMSOBJECT_TYPE,
    S3.CONTAINER_NAME as CONTAINER_NAME,
    S3.CONTAINER_DN as CONTAINER_DN,
    S3.CONTAINER_TYPE as CONTAINER_TYPE
    from
    imsAuditEvent12 LEFT JOIN imsAuditTaskSession12 ON imsAuditTaskSession12.id=imsAuditEvent12.tasksession_id LEFT JOIN
    (select parent_event_id,
    ca_concat('imsAuditEventObject12.parent_event_id',parent_event_id,'imsAuditEventObject12.object_name','imsAuditEventObject12') as OBJECT_NAME,
    ca_concat('imsAuditEventObject12.parent_event_id',parent_event_id,'imsAuditEventObject12.object_type','imsAuditEventObject12') as OBJECT_TYPE,
    ca_concat_noseq('imsAuditEventObject12.parent_event_id',parent_event_id,'imsAuditEventObject12.ID','imsAuditEventObject12') as OBJECT_ID
    from
    imsAuditEventObject12 group by parent_event_id) S1
    ON imsAuditEvent12.id = S1.parent_event_id LEFT JOIN
    (select
    parent_object_id,
    ca_concat('parent_object_id',parent_object_id,'attribute_name','imsauditobjectattributes12') as ATTRIBUTE_NAME,
    ca_concat('parent_object_id',parent_object_id,'attribute_oldvalue','imsauditobjectattributes12') as ATTRIBUTE_OLDVALUES ,
    ca_concat('parent_object_id',parent_object_id,'attribute_newvalue','imsauditobjectattributes12') as ATTRIBUTE_NEWVALUES
    from
    imsauditobjectattributes12 group by parent_object_id) S2
    ON S1.OBJECT_ID = S2.parent_object_id LEFT JOIN
    (select
    parent_event_id,
    ca_concat('parent_event_id',parent_event_id,'OBJECT_DN','imsauditobjectrelationship12') as OBJECT_DN,
    ca_concat('parent_event_id',parent_event_id,'OBJECT_TYPE','imsauditobjectrelationship12') as OBJECT_TYPE ,
    ca_concat('parent_event_id',parent_event_id,'CONTAINER_NAME','imsauditobjectrelationship12') as CONTAINER_NAME,
    ca_concat('parent_event_id',parent_event_id,'CONTAINER_DN','imsauditobjectrelationship12') as CONTAINER_DN,
    ca_concat('parent_event_id',parent_event_id,'CONTAINER_TYPE','imsauditobjectrelationship12') as CONTAINER_TYPE
    from
    imsauditobjectrelationship12 group by parent_event_id) S3
    ON imsAuditEvent12.id =S3.parent_event_id where imsauditevent12.id > 0 and imsauditevent12.id <12000 order by imsauditevent12.id ASC;
    2. Query without using functions:
    select * from imsauditeventobject12 left join imsauditevent12 on imsauditeventobject12.id=imsauditevent12.id left join imsauditobjectattributes12 on imsauditeventobject12.id=imsauditobjectattributes12.parent_object_id left join imsaudittasksession12 on imsauditevent12.tasksession_id=imsaudittasksession12.id left join imsAuditObjectRelationship12 on imsAuditEvent12.id =imsAuditObjectRelationship12.parent_event_id where imsauditevent12.id >0 and imsauditevent12.id < 12000 order by imsauditevent12.id asc;
    Thanks,
    Badri

    Hi,
    Please find the below more information about the query.
    DB version: Oracle 11g Enterprise Edition Release 11.2.0.1.0
    Below are source of the functions:
    create or replace function ca_concat( ca_key_name in varchar2,
                           ca_key_val  in varchar2,
                           ca_other_col_name in varchar2,
                           ca_tname     in varchar2 )
       return varchar2
          as
           type rc is ref cursor;
           l_str    varchar2(32000);
           l_sep    varchar2(1);
           l_val    varchar2(32000);
           l_count   number(6);
           l_cur    rc;
       begin
       l_count :=1;
       l_str := '';
           open l_cur for 'select '|| ca_other_col_name ||'
                             from '|| ca_tname || '
                            where ' || ca_key_name || ' = '
                       using ca_key_val;
           loop
               fetch l_cur into l_val;
               l_val := SUBSTR(l_val,0,102);
               exit when (l_cur%notfound or l_count > 38);
               l_str := l_str || l_sep || l_count || '.' || l_val;
               l_sep := ',';
           l_count := l_count + 1;
           end loop;
           close l_cur;
           return l_str;
       end;
      create or replace function ca_concat_noseq( ca_key_name in varchar2,
                           ca_key_val  in varchar2,
                           ca_other_col_name in varchar2,
                           ca_tname     in varchar2 )
       return varchar2
          as
           type rc is ref cursor;
           l_str    nvarchar2(32000);
           l_sep    varchar2(1);
           l_val    varchar2(32000);
           l_count   number(6);
           l_cur    rc;
       begin
       l_count :=1;
           open l_cur for 'select '||ca_other_col_name||'
                             from '|| ca_tname || '
                            where ' || ca_key_name || ' = '
                       using ca_key_val;
           loop
               fetch l_cur into l_val;
               exit when (l_cur%notfound or length(l_val)>3000 or l_count>1);
               l_str := l_str || l_sep || l_val ;
               l_sep := ',';
           l_count := l_count + 1;
           end loop;
           close l_cur;
           return l_str;
    end;
    Below are the tables structures:
    DESC imsauditevent12;
    Name                           Null     Type                                                                                                                                                                                      
    ID                             NOT NULL NUMBER                                                                                                                                                                                       
    TASKSESSION_ID                 NOT NULL NUMBER                                                                                                                                                                                       
    TASKSESSION_OID                         VARCHAR2(100)                                                                                                                                                                                
    PARENT_EVENT_OID                        VARCHAR2(100)                                                                                                                                                                                
    AUDIT_TIME                     NOT NULL TIMESTAMP(6)                                                                                                                                                                                 
    EVENT_OID                      NOT NULL VARCHAR2(100)                                                                                                                                                                                
    ADMIN_DN                       NOT NULL VARCHAR2(512)                                                                                                                                                                                
    ADMIN_NAME                              VARCHAR2(255)                                                                                                                                                                                
    EVENT_NAME                     NOT NULL VARCHAR2(255)                                                                                                                                                                                
    EVENT_DESCRIPTION                       VARCHAR2(4000)                                                                                                                                                                               
    EVENT_STATE                             VARCHAR2(100)                                                                                                                                                                                
    ENVNAME                        NOT NULL VARCHAR2(100)                                                                                                                                                                                
    ENV_OID                        NOT NULL VARCHAR2(100)                                                                                                                                                                                
    DESC imsauditeventobject12;
    Name                           Null     Type                                                                                                                                                                                         
    ID                             NOT NULL NUMBER                                                                                                                                                                                       
    PARENT_EVENT_ID                NOT NULL NUMBER                                                                                                                                                                                       
    AUDIT_TIME                     NOT NULL TIMESTAMP(6)                                                                                                                                                                                 
    OBJECT_TYPE                    NOT NULL VARCHAR2(100)                                                                                                                                                                                
    OBJECT_NAME                             VARCHAR2(255)                                                                                                                                                                                
    DESC imsauditobjectattributes12;
    Name                           Null     Type                                                                                                                                                                                         
    ID                             NOT NULL NUMBER                                                                                                                                                                                       
    PARENT_OBJECT_ID               NOT NULL NUMBER                                                                                                                                                                                       
    AUDIT_TIME                     NOT NULL TIMESTAMP(6)                                                                                                                                                                                 
    DISPLAY_NAME                            VARCHAR2(255)                                                                                                                                                                                
    ATTRIBUTE_NAME                 NOT NULL VARCHAR2(255)                                                                                                                                                                                
    ATTRIBUTE_OLDVALUE                      VARCHAR2(4000)                                                                                                                                                                               
    ATTRIBUTE_NEWVALUE                      VARCHAR2(4000)                                                                                                                                                                               
    DESC imsaudittasksession12;
    Name                           Null     Type                                                                                                                                                                                         
    ID                             NOT NULL NUMBER                                                                                                                                                                                       
    PARENT_TS_OID                           VARCHAR2(100)                                                                                                                                                                                
    PARENT_EVENT_OID                        VARCHAR2(100)                                                                                                                                                                                
    AUDIT_TIME                     NOT NULL TIMESTAMP(6)                                                                                                                                                                                 
    TASKSESSION_OID                NOT NULL VARCHAR2(100)                                                                                                                                                                                
    ADMIN_DN                       NOT NULL VARCHAR2(512)                                                                                                                                                                                
    ADMIN_NAME                              VARCHAR2(255)                                                                                                                                                                                
    TASK_NAME                               VARCHAR2(255)                                                                                                                                                                                
    TASK_TAG                       NOT NULL VARCHAR2(255)                                                                                                                                                                                
    TASK_DESCRIPTION                        VARCHAR2(4000)                                                                                                                                                                               
    TASK_PRIORITY                           NUMBER                                                                                                                                                                                       
    STATE                          NOT NULL VARCHAR2(100)                                                                                                                                                                                
    ENVNAME                        NOT NULL VARCHAR2(100)                                                                                                                                                                                
    ENV_OID                        NOT NULL VARCHAR2(100)                                                                                                                                                                
    DESC imsAuditObjectRelationship12;
    Name                           Null     Type                                                                                                                                                                                         
    ID                             NOT NULL NUMBER                                                                                                                                                                                       
    PARENT_EVENT_ID                NOT NULL NUMBER                                                                                                                                                                                       
    AUDIT_TIME                     NOT NULL TIMESTAMP(6)                                                                                                                                                                                 
    OBJECT_TYPE                    NOT NULL VARCHAR2(100)                                                                                                                                                                                
    OBJECT_DN                      NOT NULL VARCHAR2(512)                                                                                                                                                                                
    CONTAINER_TYPE                 NOT NULL VARCHAR2(100)                                                                                                                                                                                
    OBJECT_NAME                    NOT NULL VARCHAR2(255)                                                                                                                                                                                
    CONTAINER_NAME                 NOT NULL VARCHAR2(255)                                                                                                                                                                                
    CONTAINER_DN                   NOT NULL VARCHAR2(512)                                                                                                                                                                          
    OPERATION                      NOT NULL VARCHAR2(50)                                                                                                                                                                                 
    Thanks,
    Badri

  • In Oracle SQL, cannot use column in select statement and order by

    Hi,
    Is there a work around for this.
    Thanks in advance
    Pablo.

    Hi,
    943981 wrote:
    Hi All,
    This is the error I get:
    ORA-00960: ambiguous column naming in select list
    00960. 00000 - "ambiguous column naming in select list"
    *Cause:    A column name in the order-by list matches more than one select
    list columns.
    *Action:   Remove duplicate column naming in select list.
    Error at Line: 6 Column: 17That error message looks pretty clear to me. What don't you understand?
    Either
    (a) use aliases, so each column has a unique name, or
    (b) remove duplicate columns from the SELECT clause.
    Post your query. It's hard to say exactly what you're doing wrong when we don't know exactly what you're doing.
    For best results, post a complete test script (including CREATE TABLE and INSERT statements, if necessary) that people can to re-create the problem and test their ideas.
    See the forum FAQ {message:id=9360002}

  • Using Subquery in Select with Rollup (or some way to get grand total)

    I am trying to do the following (simplified the query):
    SELECT s.SYSTEM,
    (SELECT COUNT(cp1.cid) FROM cfrs cp1, systems sp1, subsystems ssp1 where cp1.priority = 'P1' AND cp1.subsystem = ssp1.subsystem AND sp1.system = ssp1.system AND sp1.system = s.system) AS P1
    FROM cfrs c, systems s, subsystems ss
    WHERE c.subsystem = ss.subsystem
    AND s.system = ss.system
    GROUP BY ROLLUP(s.SYSTEM)
    But the result of the Rollup on the P1 column is always 0 (it is not summing it up)
    How can I accomplish a Rollup (or get a grand total) of the subquery result?
    Thanks,

    How about this then:
    SQL &gt; WITH SYSTEMS AS
      2  (
      3     SELECT 'A' AS SYSTEM FROM DUAL UNION ALL
      4     SELECT 'B' AS SYSTEM FROM DUAL UNION ALL
      5     SELECT 'C' AS SYSTEM FROM DUAL
      6  ),
      7  SUBSYSTEMS AS
      8  (
      9     SELECT 'A' AS SYSTEM, '1' AS SUBSYSTEM FROM DUAL UNION ALL
    10     SELECT 'A' AS SYSTEM, '2' AS SUBSYSTEM FROM DUAL UNION ALL
    11     SELECT 'A' AS SYSTEM, '3' AS SUBSYSTEM FROM DUAL UNION ALL
    12     SELECT 'B' AS SYSTEM, '4' AS SUBSYSTEM FROM DUAL UNION ALL
    13     SELECT 'B' AS SYSTEM, '5' AS SUBSYSTEM FROM DUAL UNION ALL
    14     SELECT 'B' AS SYSTEM, '6' AS SUBSYSTEM FROM DUAL UNION ALL
    15     SELECT 'C' AS SYSTEM, '7' AS SUBSYSTEM FROM DUAL UNION ALL
    16     SELECT 'C' AS SYSTEM, '8' AS SUBSYSTEM FROM DUAL UNION ALL
    17     SELECT 'C' AS SYSTEM, '9' AS SUBSYSTEM FROM DUAL
    18  ),
    19  CFRS AS
    20  (
    21     SELECT 10 AS CID, '1' AS SUBSYSTEM, 'HIGH' AS PRIORITY FROM DUAL UNION ALL
    22     SELECT 11 AS CID, '1' AS SUBSYSTEM, 'LOW' AS PRIORITY FROM DUAL UNION ALL
    23     SELECT 12 AS CID, '1' AS SUBSYSTEM, 'MED' AS PRIORITY FROM DUAL UNION ALL
    24     SELECT 13 AS CID, '2' AS SUBSYSTEM, 'HIGH' AS PRIORITY FROM DUAL UNION ALL
    25     SELECT 14 AS CID, '2' AS SUBSYSTEM, 'MED' AS PRIORITY FROM DUAL UNION ALL
    26     SELECT 15 AS CID, '2' AS SUBSYSTEM, 'HIGH' AS PRIORITY FROM DUAL UNION ALL
    27     SELECT 16 AS CID, '3' AS SUBSYSTEM, 'LOW' AS PRIORITY FROM DUAL UNION ALL
    28     SELECT 17 AS CID, '3' AS SUBSYSTEM, 'HIGH' AS PRIORITY FROM DUAL UNION ALL
    29     SELECT 18 AS CID, '4' AS SUBSYSTEM, 'MED' AS PRIORITY FROM DUAL UNION ALL
    30     SELECT 19 AS CID, '5' AS SUBSYSTEM, 'HIGH' AS PRIORITY FROM DUAL UNION ALL
    31     SELECT 20 AS CID, '5' AS SUBSYSTEM, 'LOW' AS PRIORITY FROM DUAL UNION ALL
    32     SELECT 21 AS CID, '6' AS SUBSYSTEM, 'HIGH' AS PRIORITY FROM DUAL UNION ALL
    33     SELECT 31 AS CID, '7' AS SUBSYSTEM, 'LOW' AS PRIORITY FROM DUAL UNION ALL
    34     SELECT 41 AS CID, '8' AS SUBSYSTEM, 'HIGH' AS PRIORITY FROM DUAL UNION ALL
    35     SELECT 51 AS CID, '9' AS SUBSYSTEM, 'MED' AS PRIORITY FROM DUAL UNION ALL
    36     SELECT 61 AS CID, '9' AS SUBSYSTEM, 'MED' AS PRIORITY FROM DUAL
    37  )
    38  SELECT DECODE(SYSTEM,'ALL_SYSTEMS','Grand Total',SYSTEM) AS SYSTEM
    39  ,  MAX(DECODE(PRIORITY,'LOW',CNT,0))       AS LOW
    40  ,  MAX(DECODE(PRIORITY,'MED',CNT,0))       AS MED
    41  ,  MAX(DECODE(PRIORITY,'HIGH',CNT,0))      AS HIGH
    42  ,  MAX(DECODE(PRIORITY,'ALL_PRIOR',CNT,0)) AS SYSTEM_TOTAL
    43  FROM
    44  (
    45     SELECT DECODE(GROUPING(SYSTEMS.SYSTEM),1,'ALL_SYSTEMS',SYSTEMS.SYSTEM) AS SYSTEM
    46     , DECODE(GROUPING(CFRS.PRIORITY),1,'ALL_PRIOR',CFRS.PRIORITY) AS PRIORITY
    47     , COUNT(*) AS CNT
    48     FROM SYSTEMS
    49     JOIN SUBSYSTEMS ON SYSTEMS.SYSTEM = SUBSYSTEMS.SYSTEM
    50     JOIN CFRS ON SUBSYSTEMS.SUBSYSTEM = CFRS.SUBSYSTEM
    51     GROUP BY CUBE(SYSTEMS.SYSTEM,CFRS.PRIORITY)
    52     ORDER BY SYSTEMS.SYSTEM, CFRS.PRIORITY
    53  )
    54  GROUP BY DECODE(SYSTEM,'ALL_SYSTEMS','Grand Total',SYSTEM)
    55  ORDER BY DECODE(SYSTEM,'ALL_SYSTEMS','Grand Total',SYSTEM)
    56  /
    SYSTEM             LOW        MED       HIGH SYSTEM_TOTAL
    A                    2          2          4            8
    B                    1          1          2            4
    C                    1          2          1            4
    Grand Total          4          5          7           16Oh, BTW, use "code" wrapped in "{}" on either side to post nicely formatted code.

  • How to avoid using schema_name in select statements

    Hello
    I am in the process of developing a 3-tier database application with Delphi, using Oracle database server. When I try to to execute the following code in a query on the client application(with a logged user who has been granted select on that table):
    SELECT C1,C2
    FROM TABLE1
    WHERE ((C3 = :P1) OR (C3 IS NULL))
    AND (C4 = :P2)
    ORDER BY C5
    it raises an "ORA-00942: table or view does not exist" exception. The table exists, the user has the necessary grants, but it still doesn't work. When I put the actual schema_name before the table name it starts to work(like this):
    SELECT C1,C2
    FROM SCHEMA1.TABLE1
    WHERE ((C3 = :P1) OR (C3 IS NULL))
    AND (C4 = :P2)
    ORDER BY C5
    What am I doing wrong?

    To explain the reason for the solutions suggested.
    The problem is scope. Just like having a constant in another Delphi unit which is what you want to reference in the current unit.
    You refer to an object. Oracle scope resolution first looks in the current schema for the session. If it does not find the object there (as a table/view/synonym/etc), it looks in the public context (public synonyms). It does not traverse any other schemas as that would be a very dangerous and inefficient thing to do (e.g. imagine referring to EMP and you have access to EMP tables in JOE's and SCOTT's schemas - which EMP is the real EMP?).
    You can change the current schema for scope resolution. E.g. you're signed in as schema SCOTT. You issue an alter session set current_schema=hr_system. Now the default scope is HR_SYSTEM and no longer SCOTT. However, you're SCOTT privs are still applicable.
    Alternatively you can use synonyms or public synonyms. The latter should however not be used for application objects. Public should only be used for generic objects applicable across all application schemas.

Maybe you are looking for