Subqueris in Casestatement

Hi,
I'm trying to use the subquery in case statement in 11g it is working fine. But its throwing the ORA-00979: not a GROUP BY expression in 10g. Will 10g wont support subqueries in case statement ?
Appreciated your help.
select month,
       case when  workflow_type in (select document_type from document_type_filters where filters='initial') then 'cawv_initial_ca'
            when  workflow_type in (select document_type from document_type_filters where filters='annual') then 'cawv_annual_ca'          
       end kri,count(workflow_id) itms_total
from  me_data
where month='30-sep-11'
      and (workflow_type in (select document_type from document_type_filters where filters in ('annual','initial')
group by nvl(completed_by, 'unknown'),
         case when  workflow_type in (select document_type from document_type_filters where filters='initial') then 'cawv_initial_ca'
              when  workflow_type in (select document_type from document_type_filters where filters='annual') then 'cawv_annual_ca'         
         end; Regards,
Venkat

Hi, Venkat,
month is not in the GROUP BY clause.
I don't have an Oracle 11 database right now. I couldn't test it anyway, because I don't have those tables.
whenever you have a problem, post CREATE TABLE and INSERT statements for a little sample data, or else use commonly available tables (such as those in the scott or hr schemas) to show your problem.
Your code will be easier to debug and maintain i9and probably more efficient) if you compute kri once, in a sub-query, so that the CASE espression doesn't have to be repeated.
It will also be more efficient if you only do one sub-query using document_type_filters, like this:
WITH     got_kri          AS
     SELECT     month
     ,     CASE  (
               SELECT  MIN ( CASE  document_type_filters
                                   WHEN  'initial'     THEN  1
                             WHEN  'annual'     THEN  2
                          END
               FROM     document_type_filters
               WHERE     document_type          = m.workflow_type
               AND     document_type_filters     IN ('annual', 'initial')
                WHEN  1     THEN  'cawv_initial_ca'
                WHEN  2     THEN  'cawv_annual_ca'
          END     AS kri
     ,     workflow_id
     FROM     me_data
     WHERE     month     = '30-sep-11'     -- Use DATEs when appropriate
SELECT       month
,       kri
,       COUNT (workflow_id)     AS itms_total
FROM       got_kri
GROUP BY  month
,            kri
;Depending on you data, it could be simpler and more efficient still to join me_data and document_type_filters, rather than use a sub-query.
Edited by: Frank Kulash on Nov 7, 2011 6:26 AM
Added alternative query

Similar Messages

  • Help with Subqueries

    Hello all,
    I’m hoping to get some help with my SQL code. I’m relatively new with SQL, and this is my first time using subqueries, and I’m getting some issues. Here’s what I’m looking to do, and I’ll try to make it as least confusing as possible.
    My table contains multiple shipments each with multiple status codes for the shipment. I’m filtering for shipments containing a status code of SMRV. There might be multiple SMRV codes per shipment. Now, the problem is that an SMRV is sometimes associated with a SPLN code. If so, these codes will be assigned on the same day. My goal is to REMOVE all SMRV codes within a shipment in which the date the SMRV and SPLN codes are equal.
    So my methodology is as such.
    1. Subquery x retrieves all shipments with an SMRV code, along with the code date
    2. Subquery y looks at those shipments and retrieves the SPLN dates
    3. Outer query returns shipment #, all SMRV status codes and dates in which SMRV dates aren’t equal to an SPLN date
    Issues
    1. Running my subquery y returns a duplicate set of dates. I took care of this by using a SELECT DISTINCT function, but I’m not sure if my code is just wrong somehow.
    2. Outer query just gives me an error I don’t understand.
    ORA-06553: PLS-306: wrong number or types of arguments in call to 'OGC_X'
    06553. 00000 - "PLS-%s: %s"
    *Cause:   
    *Action:
    Error at Line: 164 Column: 29
    Maybe there is an easier way to do this, but I’ve been studying online examples and can’t find out what I’m doing wrong. Thanks in advance!
    select
    cmt.SHPMT_NUM "Shipment_Number",
    cmt.EVENT_CATG_TYPE_ID "Status Code",
    cmt.EVENT_DT "SRMV_Date"
    from
    table.shpmt shp,
    table.cmnt_and_event cmt,
    (select distinct
    cmt.EVENT_DT "SPLN_Date"
    from
    table.cmnt_and_event cmt,
    (select
    cmt.SHPMT_NUM "Shipment_Number",
    cmt.EVENT_DT "SRMV_Date"
    from
    table.cmnt_and_event cmt
    where cmt.SHPMT_NUM = '254151301'
    and cmt.EVENT_CATG_TYPE_ID IN ('SRMV')) x
    where cmt.SHPMT_NUM = x."Shipment_Number"
    and cmt.EVENT_CATG_TYPE_ID IN ('SPLN')) y
    where x."Shipment_Number" = cmt.SHPMT_NUM
    and cmt.SHPMT_NUM = shp.SHPMT_NUM
    and x."SRMV_Date" <> y."SPLN_Date" (ERROR seems to happen here)
    and cmt.EVENT_CATG_TYPE_ID IN ('SRMV')

    I have not yet tried to see if the SQL statement matches the requirements, but I have reformatted the SQL statement to highlight why you are receiving an error.
    select
      cmt.SHPMT_NUM "Shipment_Number",
      cmt.EVENT_CATG_TYPE_ID "Status Code",
      cmt.EVENT_DT "SRMV_Date"
    from
      table.shpmt shp,
      table.cmnt_and_event cmt,
      (select distinct
        cmt.EVENT_DT "SPLN_Date"
      from
        table.cmnt_and_event cmt,
        (select
          cmt.SHPMT_NUM "Shipment_Number",
          cmt.EVENT_DT "SRMV_Date"
        from
          table.cmnt_and_event cmt
        where
          cmt.SHPMT_NUM = '254151301'
          and cmt.EVENT_CATG_TYPE_ID IN ('SRMV')
        ) x
      where
        cmt.SHPMT_NUM = x."Shipment_Number"
        and cmt.EVENT_CATG_TYPE_ID IN ('SPLN')
      ) y
    where
      x."Shipment_Number" = cmt.SHPMT_NUM
      and cmt.SHPMT_NUM = shp.SHPMT_NUM
      and x."SRMV_Date" != y."SPLN_Date"
      and cmt.EVENT_CATG_TYPE_ID IN ('SRMV')In the above, I changed the less than/greater than combination into the equivalent != so that is will print on the forum web page.
    The reason for the error is that the inline view that you have aliased as X is inside the inline view that you have aliased as Y. The X alias is not visible to the final WHERE clause, and that is why the third line in the WHERE clause is throwing an error (the first one will also). Because the X inline view is inside the Y inline view, you must tell the optimizer how to join the table aliased as SHP to the table aliased as CMT to the inline view X in the second to the last WHERE clause (where you have cmt.SHPMT_NUM = x."Shipment_Number").
    Charles Hooper
    Co-author of "Expert Oracle Practices: Oracle Database Administration from the Oak Table"
    http://hoopercharles.wordpress.com/
    IT Manager/Oracle DBA
    K&M Machine-Fabricating, Inc.
    Edited by: Charles Hooper on Oct 15, 2010 9:46 AM
    The table alias as SHP is not in the inline view Y.

  • Adding the results of subqueries, where one subquery returns no rows

    I am creating a complex SQL statement- many of the columns consist of the sum of two subqueries. Here is a simplified example:
    SELECT NAME, ID,
    (SELECT AMT1 FROM TABLE1 WHERE ID = 111) + (SELECT AMT2 FROM TABLE2 WHERE ID = 222),
    (SELECT AMT3 FROM TABLE3 WHERE ID = 333) + (SELECT AMT4 FROM TABLE4 WHERE ID = 444),
    FROM TABLE
    WHERE...
    The problem is, within one select item, if one subquery returns no rows and the other returns a row of data, the sum of the two is displayed as zero. For example, if 'SELECT AMT1 FROM TABLE1 WHERE ID = 111' returns a row, with a value of AMT1 = 1000, and 'SELECT AMT2 FROM TABLE2 WHERE ID = 222' returns no rows, the result is displayed as 0, not 1000. It reminds me of when you add a number and a NULL, and get NULL - the number gets ignored.
    Is there a way to embed some conditional logic in the subquery, to say 'if no rows returned, AMT = 0, else AMT = value'? Any help would be appreciated.

    Yikes, you appear to have stumbled upon DMFH!
    You can use NVL like this -
    SQL> select
      2    (select 1 from dual) + (select 2 from dual) x
      3  from dual;
             X
             3
    SQL> edi
    Wrote file afiedt.sql
      1  select
      2    (select 1 from dual) + (select 2 from dual where 0 = 1) x
      3* from dual
    SQL> /
             X
    SQL> edi
    Wrote file afiedt.sql
      1  select
      2    (select 1 from dual) + nvl((select 2 from dual where 0 = 1),0) x
      3* from dual
    SQL> /
             X
             1
    SQL>(DMFH = Data Model From Hell)

  • Using full outer join of subqueries named using with clause

    Hi,
    I am trying to create a view which is having 2 subqueries vol1 & vol2 with WITH clause. I am joining those 2 subqueries in the main query with FULL OUTER JOIN.
    When i compile that view in a tool like pl/sql developer, It has been compiled successfully.
    But when i call the view creation script from SQL command prompt, It is throwing error as
    from vol1 FULL JOIN vol2 o ON (vol1.ct_reference = vol2.ct_reference and vol1.table_name = vol2.table_name
    ERROR at line 29:
    ORA-00942: table or view does not exist
    Kindly advise whats going wrong.

    that's line 29. Maybe you get a better idea if you strip your operation of all the unneccessary elements until it works.
    There are some known bugs with subquery factoring (aka with clause) and also with ANSI join syntax, but it is hard to tell what happens here based on your description. But one thing is strange - if it is not a result of formatting (not formatting): I would expect the asterisk beneath the unknown table and not beneath the key word FULL.
    P.S.: my editor makes me think it's rather a proportional font thing. Have I already said that I don't like proportional font for SQL code examples?

  • Materialized view and  subqueries

    Hi everyone,
    I have a big SQL which has a lot of (select (select ...) as)
    statements (subqueries inside the relational projection
    statement). In Oracle 8i, as in 9i, I can4t create a
    materialized view with this kind on query. It gives me the
    error 'subqueries not allowed here'.
    But in Oracle 8i there is a workaround: create a view with the
    big SQL, and create a materialized view just with select * from
    BIGSQL.
    Now, in Oracle 9i it4not working anymore.
    Anyone can help me? It4s almost impossible to rewrite the query.
    It4s too big.
    TIA
    Flavio

    Hi,
    Oracle uses materialized views (also known as snapshots in prior releases) to replicate data to non-master sites in a replication environment and to cache expensive queries in a data warehouse environment.
    A materialized view is a replica of a target master from a single point in time. The master can be either a master table at a master site or a master materialized view at a materialized view site. Whereas in multimaster replication tables are continuously updated by other master sites, materialized views are updated from one or more masters through individual batch updates, known as a refreshes, from a single master site or master materialized view site.
    Regards,
    Jonathan Ferreira - Brazil
    http://www.ebs11i.com.br

  • LIKE operator in multiple-row subqueries

    Hello,
    in a test i saw 2 questions:
    Which operator can be used with a multiple-row subquery?
    A. =
    B. LIKE
    C. BETWEEN
    D. NOT IN
    E. IS
    F. <>
    Answer: D
    and
    Which two statements about subqueries are true? (Choose two.)
    A. A single row subquery can retrieve data from only one table.
    B. A SQL query statement cannot display data from table B that is referred to in its
    subquery, unless table B is included in the main query's FROM clause.
    C. A SQL query statement can display data from table B that is referred to in its subquery,
    without including table B in its own FROM clause.
    D A single row subquery can retrieve data from more than one table.
    E. A single row subquery cannot be used in a condition where the LIKE operator is used for
    comparison.
    F. A multiple-row subquery cannot be used in a condition where the LIKE operator is used for
    comparison.
    Answer: B & D
    But in the last question, why F is not correct? because the 1st question says that only NOT IN can be used in multiple-row subqueries. I'm confused
    Thanks

    only two, but what principle applies if not specified? First two correct?
    however, in explanation i saw something like this (regarding to the 2nd question)
    Incorrect Answers
    A: A single row sub-query can retrieve data from more than one table.
    C: A SQL query statement cannot display data from table B that is referred to in its subquery,
    unless table B is included in the main query's FROM clause.
    E: A single row sub-query can be used in a condition where the LIKE operator is used for
    comparison.
    F: A multiple-row sub-query can be used in a condition where the LIKE operator is used for
    comparison.
    so, at F: can be used or nor? they aren't so clear. only which operators can be used in multiple-row subquery?

  • Equivalent for TOP 1 of SQL Server used in subqueries

    Hi all,
    I am trying to migrate a sql query from SQL Server to Oracle 9i, which uses the SQL Server TOP keyword in correlated subqueries.
    How should I write it in Oracle?
    The query is more complicated, but in principle looks like:
    SELECT TAB1.t1_id, TAB2_t2_id,
    ISNULL((select top 1 val_num
    from values where values.val_id = TAB1.val_id ) ,0),
    TAB1.date,
         (select top 1 TAB3.t3_id from TAB3 where TAB3.name = TAB1.name)
    FROM TAB1, TAB2
    WHERE TAB1.org_id = TAB2.org_id
         AND TAB1.date > TO_DATE('2006-01-01', 'YYYY-MM-DD')
         TAB2.required IS NOT NULL
    If I would remove in each subquery the "top 1" and add "and rownum = 1", it will not work.
    Any suggestions?
    Thanks,
    Paul

    http://www.ispirer.com/doc/sqlways38/Output/SQLWays-1-044.html

  • ODT 11g beta TableAdapter Configuarion Wizard subqueries

    To me it seems like the wizard does not like $ characters when there are subqueries. I've tryed to follow the design guidelines from the tutorial at http://www.asp.net/learn/data-access/tutorial-01-cs.aspx
    but with a connection to an Oracle database instead. Of course you could use JOIN instead of subqueries, but that will affect the auto-generated methods for inserting, updating, and deleting negatively and that is not what I want.
    Example:
    SELECT MYDB."ABC$TABLE1".ID,
    MYDB."ABC$TABLE2".TYPE,
    (SELECT MYDB."ABC$TYPE1".NAME
    FROM MYDB."ABC$TYPE1"
    WHERE MYDB."ABC$TYPE1".TYPE = MYDB."ABC$TABLE1".TYPE) AS TYPE_NAME
    FROM MYDB."ABC$TABLE1"
    In the Query Designer a similar statment generates:
    Error in SELECT clause: expression near 'SELECT'.
    Error in SELECT clause: expression near 'FROM'.
    Missing FROM clause.
    Error in SELECT clause: expression near ','.
    Unable to parse query text.
    but it gives me a proper output in the result area!?
    If I try without inclosing " characters I get:
    Error in SELECT clause: expression near '$'.
    Missing FROM clause.
    Error in SELECT clause: expression near ','.
    Error in SELECT clause: expression near 'SELECT'.
    Error in SELECT clause: expression near 'FROM'.
    Unable to parse query text.
    Not very strange perhaps, but actually again I get a proper output in the result area!?
    Any ideas/workarounds? Bug or feature? ;-)

    What happens when you execute this SQL from the Oracle Query Window? I am by no means a SQL guru but there are different dialects between what is expected for SQL Server and Oracle. The fastest way to test this is to use query window (NOT Query Designer). If you get an error with Oracle Query window, which just passes it on to Oracle, it must be invalid SQL. If you don't it may be a bug in our wizard.
    Please let me know what you find out and perhaps provide me a join that reproduces this using the HR schema.

  • HTMLDB_ITEM with scalar subqueries

    How does HTMLDB_ITEM work with scalar subqueries?
    Suppose I want to do something like
    select
    c1,c2,c3,
    (select htmldb_item.checkbox(1,c4)
    from sometable where ....)
    from ...
    If the scalar subquery doesnt return a row, I dont get my checkbox.
    How else can I do this? Thanks

    Sort of. Let me try to explain what I am really trying to do.
    create table class
    class_id int primary key,
    class_name varchar2(25),
    class_start_date date,
    class_end_date date
    create table students
    student_id int primary key,
    sname varchar2(25),
    address varchar2(25)
    create table attendance
    student_id int,
    class_id int,
    registered varchar2(1) not null check (registered in ('Y','N')),
    reg_date date
    Given a list of students and a list of classes,I want to put up a updatable form on the attendance table. If a record exists in the attendance table, I should be able to upadte it. If it doesnt exist, the fields (registered and reg_date) should still be shown and if I enter a value in them, create the row (otherwise dont create the row!)
    How can I do this? Thanks

  • Can we use subqueries in Web Intelligence

    Hi,
    I would like to know how can we use subqueries  in WebIntelligence Report.
    Regards,
    Swapna.

    hi swapna
    yes you can create sub query in webi
    just go to the webi rich editor
    where you drag n drop the objects
    on left hand side of the line item objects which you are above the select for desinging report you will have combined query option just click that
    ylou will find options in the prompt pannel there you can use sub query by choosing AND  OR options depending requirement
    thanks

  • Correlated Subqueries, NOT EXISTS & Anti Joins - Clarification

    I am a bit confused now regarding correlated subqueries and the NOT EXISTS operator (I had originally thought I understood but am all mixed up now!)
    I was reading around and have gathered that if one were to use EXISTS that this isnt the preferred method, and that the query should actually be re-written as a join (im guessing INNER JOIN) to improve performance.
    NOT EXISTS is also not a recommended method from what I read as well.
    Correlated subqueries in general are not recommended for performance issues, since the subquery needs to be executed once for every row returned by the outer query.
    I was reading up on anti joins, and found that a lot of people referred to anti joins with the use of NOT EXISTS and a correlated subquery, which if my above understanding is correct is super bad in performance as it combines two things that people dont recommend.
    I was wondering for anti joins, is there any other way to write them besides a NOT EXISTS with a correlated subquery?
    Essentially what would be the most efficient way of writing an anti join? Or when Im trying to find all the rows that are NOT a common match between two tables.

    Hi,
    chillychin wrote:
    I am a bit confused now regarding correlated subqueries and the NOT EXISTS operator (I had originally thought I understood but am all mixed up now!)That's easy to understand! This is a topic that does not lend itself to easy, general solutions. So much depends on the circumstances of a particular query that you can never honestly say anything like "EXISTS is bad".
    I was reading around and have gathered that if one were to use EXISTS that this isnt the preferred method, and that the query should actually be re-written as a join (im guessing INNER JOIN) to improve performance. It depends. EXISTS and joins do different things. For example, when you have a one-to-many relationship, joining can increase the number of rows. Even if the join is faster than EXISTS, you may have the additional cost of doing a GROUP BY or SELECT DISTINCT to get just one copy of each row.
    NOT EXISTS is also not a recommended method from what I read as well.
    Correlated subqueries in general are not recommended for performance issues, since the subquery needs to be executed once for every row returned by the outer query.There's a lot of truth in that. However, results of coirrelated queries can be cached. That is, the system may remeber the value of a correlation variable and the value it retuned, so the next time you need to run the sub-query for the same value, it will just return the cached result, and not actually run the query again.
    Remember that performance is only one consideration. Sometimes performance is extremely important, but sometimes it is not important at all. Whether a query is easy to understand and maintain is another consideration, that is sometimes more important than performace.
    The optimizer may re-write your code in any case. When perforance really is an issue, there's no substitute for doing a EXPLAIN PLAN, finding out what's making the query slow, and addressing those issues.
    I was reading up on anti joins, and found that a lot of people referred to anti joins with the use of NOT EXISTS and a correlated subquery, which if my above understanding is correct is super bad in performance as it combines two things that people dont recommend. It's actually only one thing that the people who don't recommend it don't recommend. EXISTS sub-queries are always correlated. (Well, almost always. In over 20 years of writing Oracle queries, I only remember seeing one uncorrelated EXISTS sub-query that wasn't a mistake, and that was in a forum question that might have been hypothetical.) Nobody worth listening to objects to EXISTS because it is EXISTS, or to a correlated sub-query because it is correlated. They object to things because they are slow (or confusing, or fragile, but you seem to be concerned with performance, so let's just say slow for now.) If someone tires to avoid an EXISTS sub-query, it precisely because the sub-query is correlated, and that is only an objection because they suspect the correlation will make it slow.
    I was wondering for anti joins, is there any other way to write them besides a NOT EXISTS with a correlated subquery?As the name implies, you can use a join.
    SELECT     d.*
    FROM          scott.dept     d
    LEFT OUTER JOIN     scott.emp     e  ON     d.deptno  = e.deptno
    WHERE     e.deptno     IS NULL
    ;is an anti-join, showing details about the departments that have no employees.
    Essentially what would be the most efficient way of writing an anti join? Or when Im trying to find all the rows that are NOT a common match between two tables.Anytime you can use EXISTS, you can also use IN, or a join. Personally, I tend to use the in the reverse of that order: I'll generally try it with a join first. If that looks like a problem, then I'll try IN. The query above can also be done like this:
    SELECT     *
    FROM     scott.dept
    WHERE     deptno     NOT IN (
                      SELECT  deptno
                      FROM    scott.emp
                      WHERE   deptno   IS NOT NULL   -- If needed
    ;Failing that, I'll try EXISTS.
    Sometimes other methods are useful, too. For example, if we only need to know the deptnos that exist in scott.dept but not scott.emp, and no other information about those departments, then we can say:
    SELECT  deptno
    FROM    scott.dept
        MINUS
    SELECT  deptno
    FROM    scott.emp
    ;

  • Correlated subqueries

    what is the use of correlated subqueries and exists and not exists operator.
    what is correlated update, correlated delete
    thx
    pk

    First step is to look for "correlated" into the on-line doc :
    http://www.oracle.com/pls/db92/db92.drilldown?levelnum=2&toplevel=a96540&method=FULL&chapters=0&book=&wildcards=1&preference=&expand_all=&verb=&word=correlated#a96540
    That may help you.
    Nicolas.

  • Correlated subqueries in webi/designer

    Hi,
    i want to know how correlated subqueries can be achieved in web intelligence/universe.
    If the correlated subquery is in the where clause of the sql, then it can be achieved by creating a predefined query filter in the universe.
    The below is a simple example. In my universe i dont have a join between customers and fact_accounts.
    SELECT
    account_number,
    account_balance,
    (select account_name from customers where account_NO=fa.account_number)
    FROM fact_accounts fa
    WHERE balance_date between '01-jan-2014' and '30-apr-2014'
    how to achieve the above subquery in webi or universe
    Regards

    Would you please confirm that CQL does NOT support correlated sub-queries?

  • Column Level Subqueries

    I am converting a MS SQL Server 7.0 database to Oracle 8i.
    Currently, I run into problems to convert column-level subqueries
    into Oracle. To give an example, I have the following SQL Server
    7.0 query:
    select col_a =
    case
    when ( a > 0 ) then 1
    when ( a < 0 ) then -1
    else 0
    from table_a;
    How do I convert it into Oracle? I tried to use DECODE and it
    didn't work in this case. Any other alternative? Please help.
    Thanks.
    - Brian
    null

    It works! Thanks a lot. I just wish the documentation could have
    provided examples like that.
    -Brian
    Anish (guest) wrote:
    : You hv to use sign() function within decode.
    : Hope that helps.
    null

  • Reuse a promt/filter for a universe in some subqueries

    We want to use one defined promt in our BO universe inside 4 subqueries in CR but when we execute the report it apears 4 time, yes the same promt apear 4 times in my promt panel any idea to only appear one promt for 4 subqueries.

    Dennis, are you able to link the sub reports to the main reports ?  you may need to create some sort of formula in the main report, and use that to let the subs link up.  Of course, then you must go to the sub reports and make sure there params are looking at the links you have created.  HTH

Maybe you are looking for

  • RE: Appending a link to a message

    (Sorry, removed the signature now) Hi, I am using the "TextSetMessage" token to append a new line to a message. The new line is a URL. All works OK, except that Groupwise 6.5 sp5 does not consider the URL a link, unless the user changes the message f

  • Error while executing Form 16

    hi Gurus, can you help me to solve the following issue: While i m executing the form 16, i m getting the error, Device type unsuitable for ADS documents. How to solve this one? Regards, hem

  • How to add multiple entries at once

    Hi, I need to define Tax Jurisdiction codes under tax on sales/purchases node and i have almost thousands of entries. Is there a way to add all at once ???? Please let me know.. Thanks, adv

  • Why is mountain lion so slow

    I have been trying to download... why is it so slow??

  • 3710 How do I get the back cover off?

    3710 How do I get the back cover off? I had it off once to put the battery in; now it appears to be stuck. I 'm trying to follow the pictorial instructions, but it is not budging. Solved! Go to Solution.