Subquery in GROUP BY CLAUSE

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

Hello

This is 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 it (and I was at a state fair, a rodeo and a picnic!)

Interestingly, if I copy the expression in the GROUP BY clause from 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 expression

Despite what this book says you can use a subquery-IN 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 anyway, is not as clear to use the same exact example.)

Tags: Database

Similar Questions

  • Subquery in the select clause and not "a group by expression" error.

    Hi all
    I hope someone out there can help me out with this one. I have a sql query that performs a subquery in the select case combined with an aggregate function and gives me a "not a group by expression.

    I created a simplified example
     SELECT COUNT(*)                     ,
      ai.invoice_num invoice_number      ,
      ai.description invoice_description ,
      (SELECT poh.po_header_id
           FROM po_headers poh ,
          po_distributions pod
          WHERE pod.po_distribution_id = aid.po_distribution_id
        AND pod.po_header_id           = poh.po_header_id
        ) po_number
         FROM ap_invoice_distributions aid ,
        ap_invoices ai
        WHERE ai.invoice_id = 1476932
      AND aid.project_id    = 8608   
      AND aid.task_id       = 462202  
      AND ai.invoice_id     = aid.invoice_id
     GROUP BY ai.invoice_num,
                    ai.description;
    I'm sure he expected me to add the po_number to the group by clause, but this does not work and gives the error "invalid identifier".

    Can someone suggest a way for a new concert the query so that I can add po_number to my education by clause.

    Kris

    You should try either:

    SELECT COUNT (*),
    AI.invoice_num invoice_number,
    have. Description invoice_description,
    (SELECT poh.po_header_id
    OF po_headers poh,.
    pod po_distributions
    WHERE pod.po_distribution_id = aid.po_distribution_id
    AND pod.po_header_id = poh.po_header_id
    ) po_number
    HELP ap_invoice_distributions.
    ap_invoices AI
    WHERE ai.invoice_id = 1476932
    AND aid.project_id = 8608
    AND aid.task_id = 462202
    AND ai.invoice_id = aid.invoice_id
    Ai.invoice_num GROUP,
    have. Description, aid.po_distribution_id;

    or

    SELECT COUNT (*),
    AI.invoice_num invoice_number,
    have. Description invoice_description,
    MAX ((SELECT poh.po_header_id
    OF po_headers poh,.
    pod po_distributions
    WHERE pod.po_distribution_id = aid.po_distribution_id
    AND pod.po_header_id = poh.po_header_id
    po_number))
    HELP ap_invoice_distributions.
    ap_invoices AI
    WHERE ai.invoice_id = 1476932
    AND aid.project_id = 8608
    AND aid.task_id = 462202
    AND ai.invoice_id = aid.invoice_id
    Ai.invoice_num GROUP,
    have. Description;

  • A subquery in the From Clause

    How can I model the RPD with the sub query that has the subquery in the from Clause.

    SELECT

    o948938. CONSOLIDATED_NAME,

    (SUM (o948992. YTD_COMPLETED)) / (SUM (TOTAL_OCC_AP)) AS C_1,.

    SUM (TOTAL_OCC_AP) AS TOTAL_OCC_AP,

    Of

    ORG_DIM o948938,

    TIME_MONTHLY_DIM o948963,

    INSPECTION_FACT o948992,

    (SELECT TDS_NUM,

    MONTH_ID,

    SUM (TOTAL_APTS) TOTAL_AP,

    OF SUMMARY_FACT

    TDS_NUM GROUP,

    MONTH_ID

    ) O949126

    WHERE (o949126. MONTH_ID = o948992. MONTH_ID (+)

    AND o949126. TDS_NUM = o948992. TDS_NUM (+)

    AND (o948938. TDS_NUM = o949126. TDS_NUM)

    AND (O948963. MONTH_ID = O949126. MONTH_ID))

    Group

    O948938. NEW_BOROUGH_GROUPING

    Hello

    You can do this via an opaque view.

    You can also do this by modeling the cumulative value as a calculation LOGIC in the group by aggregation "pinned" to a specific dimension hierarchy that reflects consolidation in the online posting.

    Hope this helps,

    Robert.

  • A query containing a subquery and Group By all-in-one

    Hi people,
    Any interesting fact but nerve racking situation I have here. I have a question that I have to do counts and amounts and I also need to have a Sub inside query. When I run my application, I get an error like this:

    Error in the command line column: 4:36
    Error report:
    SQL error: ORA-00979: not a GROUP BY expression
    00979 00000 - "not a GROUP BY expression"
    * Cause:
    * Action:

    Here's my query:
    select distinct to_char(c.start_date,'YYYY') start_date,
             substr(acc.account_num,1,12) account_number,
           ( select acc2.account_desc from student_account  acc2
             where  acc2.account_num = acc.account_num 
             and    acc2.account_type = 'A'
           ),
           COUNT(distinct(s.student_id))
    from student s,
           student_account acc,
           course   c
    where s.course_id = c.course_id
    and     s.account_num = acc.account_num
    and    to_char(c.start_date, 'YYYY/MM/DD') between '2004/01/01' and '2009/12/31'
    group by to_char(c.start_date,'YYYY'), substr(acc.account_num,1,12)
    order by 1;
    If I replace it with the acc.account_num (subquery) with a number that is in the database, then my request works well.

    Published by: Roxyrollers on March 29, 2011 16:45

    Hello

    We don't know what you want. It would really help if you posted some examples of data (CREATE TABLE and INSERT statements) and the results desired from these data.

    Are you sure that the scalar subquery will return ever more than one line? If so, you can wrap in a MIN or MAX aggregate function, as I've suggested before:

     select distinct to_char(c.start_date,'YYYY') start_date,
             substr(acc.account_num,1,12) account_number,
       MIN ( ( select acc2.account_desc from student_account  acc2     -- Changed
             where  acc2.account_num = acc.account_num
             and    acc2.account_type = 'A'
           ) ),                                   -- Changed
           COUNT(distinct(s.student_id))
    from student s,
           student_account acc,
           course   c
    where s.course_id = c.course_id
    and     s.account_num = acc.account_num
    and    to_char(c.start_date, 'YYYY/MM/DD') between '2004/01/01' and '2009/12/31'
    group by to_char(c.start_date,'YYYY'), substr(acc.acct_acc_num,1,12)
    order by 1;
    

    It seems that you could also simplify the query and make more fast, eliminating the scalar subquery. The table there is already part of the main query, you can do something like this:

    SELECT    TO_CHAR (c.start_date, 'YYYY')     AS start_date
    ,         SUBSTR (acc.account_num, 1, 12)      AS account_number
    ,       MIN ( CASE
                        WHEN  acc.account_type = 'A'
                  THEN  account_desc
                    END
               )                         AS a_desc
    ,         COUNT (DISTINCT s.student_id)          AS student_id_cnt
    FROM       student            s
    ,       student_account     acc
    ,       course          c
    WHERE       s.course_id          = c.course_id
    AND       s.account_num          = acc.account_num
    AND       c.start_date          BETWEEN DATE '2004-01-01'
                          AND     DATE '2009-12-31'
    GROUP BY  TO_CHAR (c.start_date, 'YYYY')
    ,            SUBSTR (acc.acct_acc_num, 1, 12)
    ORDER BY  start_date;
    

    I guess that course.start_date is a DATE. Instead of converting each start_date to string (so you can see if it is in the right range), it is more efficient and less prone to error, compared to other DATEs, as shown above.

    It is very strange that you

    substr(acc.account_num,1,12)
    

    in the select clause, but

    substr(acc.acct_acc_num,1,12)
    

    in the GROUP BY clause. Did you mean having the same column in both places?

    Yet once, without seeing some examples of data (CREATE TABLE and INSERT statements) and the results desired from this data, I can't do much.

  • Concatenation of data with the GROUP BY clause

    Hi again!

    Following my previous thread...
    Re: Need help with RANK() on data ZERO

    I tried to apply the GROUP BY clause instead of preforming my query with RANK() to manage records NULL... I have a scenario where I also need to concatenate data from several lines.

    CREATE TABLE T_EMP (NUMBER OF EMP_NO, NAME VARCHAR2 (20));
    INSERT INTO T_EMP VALUES (1001, 'MARK');
    INSERT INTO T_EMP VALUES (1002, 'DAVID');
    INSERT INTO T_EMP VALUES (1003, "SHAUN");
    INSERT INTO T_EMP VALUES (1004, "JILL");

    CREATE TABLE T_EMP_DEPT (NUMBER OF EMP_NO, DEPT_NO NUMBER);
    INSERT INTO T_EMP_DEPT VALUES (1001, 10);
    INSERT INTO T_EMP_DEPT VALUES (1001, 20);
    INSERT INTO T_EMP_DEPT VALUES (1002, 10);
    INSERT INTO T_EMP_DEPT VALUES (1002, 20);
    INSERT INTO T_EMP_DEPT VALUES (1002, 30);
    INSERT INTO T_EMP_DEPT VALUES (1003, 20);
    INSERT INTO T_EMP_DEPT VALUES (1003, 30);
    INSERT INTO T_EMP_DEPT VALUES (1004, 10);

    CREATE TABLE T_EMP_VISITS (NUMBER OF EMP_NO, DEPT_NO NUMBER, VISITED DATE);
    INSERT INTO T_EMP_VISITS VALUES (1001, 10, 1 JAN 2009');
    INSERT INTO T_EMP_VISITS VALUES (1002, 10, 1 JAN 2009');
    INSERT INTO T_EMP_VISITS VALUES (1002, 30, 11 APR 2009');
    INSERT INTO T_EMP_VISITS VALUES (1003, 20, 3 MAY 2009');
    INSERT INTO T_EMP_VISITS VALUES (1003, 30: 14 FEB 2009');
    COMMIT;

    I have a T_EMP master table that stores the name and number of the emp. Each emp is required to visit some departments. This mapping is stored in the T_EMP_DEPT table. An employee can visit one or more departments. T_EMP_VISITS table stores the dates where the employee visited the services required. I need to view the report which should show when an employee all completed visits, which is the maximum date when it finished to visit all departments. If he did not visit any of the report should display date max, otherwise NULL. I was able to do using GROUP BY such proposed by Salim, but how do I show a list separated by commas of the services required for an employee in the same query.

    SELECT
    EMP_NO,
    NAME,
    MAX (DEPT_NO) KEEP (DENSE_RANK LAST ORDER BY VISITED) MAX_DEPT_NO,.
    MAX (VISITED) KEEP (DENSE_RANK LAST ORDER PER VISIT) VISITS_COMP
    DE)
    SELECT
    T_EMP. EMP_NO,
    NAME,
    T_EMP_DEPT. DEPT_NO,
    VISITED
    OF T_EMP
    LEFT OUTER JOIN T_EMP_DEPT
    ON T_EMP. EMP_NO = T_EMP_DEPT. EMP_NO
    LEFT OUTER JOIN T_EMP_VISITS
    ON T_EMP_DEPT. EMP_NO = T_EMP_VISITS. EMP_NO
    AND T_EMP_DEPT. DEPT_NO = T_EMP_VISITS. DEPT_NO)
    GROUP EMP_NO, NAME;

    Output
    EMP_NO NAME MAX_DEPT_NO VISITS_COMP
    1001 MARK 20
    1002 DAVID 20
    1003 SHAUN 20 3 MAY 09
    JILL 1004

    Power required
    EMP_NO NAME REQ_DEPTS MAX_DEPT_NO VISITS_COMP
    1001 MARC 20 10.20
    1002 DAVID 10,20,30 20
    1003 SHAUN 20,30 20 3 MAY 09
    JILL 10 1004

    Can we do this in a single query?

    Hello

    user512647 wrote:
    ... Sanjay
    The query you provided that stragg() use seems to work but my requirement is not in the result set. I don't know how to use stragg with
    MAX (DEPT_NO) KEEP (DENSE_RANK LAST ORDER BY VISITED) MAX_DEPT_NO,.
    MAX (VISITED) KEEP (DENSE_RANK LAST ORDER PER VISIT) VISITS_COMP
    I need more, these two columns these gives me the date when they have completed all visits. If they missed any Department then the result must be NULL in the VISITS_COMP field.

    Just add them to the SELECT clause:

    SELECT    t_emp.emp_no,
           name,
           STRAGG (t_emp_dept.dept_no)     AS deptno,
           MAX (t_emp_dept.dept_no) KEEP (DENSE_RANK LAST ORDER BY visited)
                                      AS max_dept_no,
           MAX (visited)                      AS visits_comp
    FROM             t_emp
    LEFT OUTER JOIN      t_emp_dept     ON   t_emp.emp_no     = t_emp_dept.emp_no
    LEFT OUTER JOIN      t_emp_visits     ON   t_emp_dept.emp_no     = t_emp_visits.emp_no
                                 AND  t_emp_dept.dept_no = t_emp_visits.dept_no
    GROUP BY  t_emp.emp_no
    ,            name
    ;
    

    The column called visit_comp is simply the last visited, regardless of how the employee visited departments.
    If you want to have the NULL value if the employee has not yet visited all 3 departments:

    ...       CASE
              WHEN  COUNT (DISTINCT t_emp_dept.dept_no) = 3
              THEN  MAX (visited)
           END                    AS visits_comp
    

    The 'magic number' 3 is the total number of departments.
    If you want to understand the correct value of that at the time of the execution of the query, replace the code literal 3 hard with a scalar subquery.

    Note that 'KEEP MAX (x) (DENSE_RANK OVER LAST SERVICE BY x)' (where the exact same column is used as an argument and that the ORDER BY column) is just "MAX (x)".

  • Doubts formidable wrt "select", "join" and "group by" clause to calm a while...

    Dear all,

    Kindly advise on below 2 doubts which have been daunting for quiet some time. The bottom has forced our requests to take alternative routes to receive solutions.

    Doubt 1) is it possible for us to use 'select (*)' with a group and a join clause, if we have at least 2/3 tables with minimum 15-20 columns... given the constraint of having to add all the names column in the group by clause.

    Question 2) is it possible to use "select" (*) with the exception of a single column of the table?
    That is to say, I hate the output of a statement select (*) to have the entire field except a field in a table

    Ask your advisor for the same thing. Excuse me because I have no examples to illustrate this point in time. A successful idea will do.

    Thank you and best regards,

    Séverine Suresh

    Hey, Sebastian,

    Séverine Suresh - 3035408 wrote:

    Dear all,

    Kindly advise on below 2 doubts which have been daunting for quiet some time. The bottom has forced our requests to take alternative routes to receive solutions.

    Doubt 1) is it possible for us to use 'select (*)' with a group and a join clause, if we have at least 2/3 tables with minimum 15-20 columns... given the constraint of having to add all the names column in the group by clause.

    Sure.  If you had problems, you did it wrong.  Your postal code, examples of data (CREATE TABLE and INSERT statements) and the results desired from these data.

    Check out the Forum FAQ: Re: 2. How can I ask a question on the forums?

    Normally, you don't want to ' SELECT *...» "in a join.  Are most joins are equijoins, ' SELECT *...» "produced 2 copies of / columns used for Assembly.  In addition, many tables have columns (for example, modified_date) that are not necessary in most applications.

    All columns must be included explicitly in a GROUP BY clause. You cannot use * it.

    You can not have parentheses around the * in ' SELECT *...» ».  You might think 'SELECT COUNT (*) '

    Question 2) is it possible to use "select" (*) with the exception of a single column of the table?
    That is to say, I hate the output of a statement select (*) to have the entire field except a field in a table

    ...

    No.; If you don't want a particular column in the result set, you cannot use "SELECT *...» ».

    Your front end can have so as not to display a column in the result set.  For example, in SQL * more:

    COLUMN modified_date NOPRINT

    means that you won't see any column called modified_date.

  • How to INSERT a SELECT statement with a GROUP BY clause on a table with an IDENTITY column?

    n an application, I intend to truncate and insertion on a 12 c Oracle database, but have found this problem with a IDENTITY column. Even if the INSERT... SELECT statement works on most SELECT uses I tried, if this statement was also a GROUP BY clause, it does not work, delivering a "ORA-00979: not a GROUP BY expression ' complaint. Some examples of code:

    create table aux ( owner_name varchar2(20), pet varchar2(20) ); 

    insert into aux values ('Scott', 'dog');

    insert into aux values ('Mike', 'dog');

    insert into aux values ('Mike', 'cat');

    insert into aux values ('John', 'turtle'); 


    create table T1 (

    id number generated always as identity,

    owner_name varchar2(20),

    pet_count number );

    select owner_name, count(*) as pet_count from aux group by owner_name; -- works just fine

    insert into T1 (owner_name, pet_count) select owner_name, count(*) as pet_count from aux group by owner_name; -- doesn't work

    The select statement works by itself, but it fails as an INSERT... SELECT statement.

    Appreciate the help!

    Looks like a bug. You must open the SR with Oracle. Meanwhile, you could materialize select:

    SQL > insert into T1 (owner_name, pet_count)
    2 with t as (select / * + materialize * / owner_name, count (*) as pet_count to the owner_name group)
    3. Select owner_name, pet_count t
    4.

    3 lines were created.

    SQL > select * from t1;

    ID OWNER_NAME PET_COUNT
    ---------- -------------------- ----------
    1 John                          1
    Scott 2 1
    3 Mike                          2

    SQL >

    Keep in mind index THAT MATERIALIZE is undocumented.

    SY.

  • Group by clause

    Hello

    You can use group by clause with COUNT function...

    In the reports, I have to count the stattus data_set group... If I use COUNT (data_set), it gives me 2 different ranks

    1 for the race and the other to succeed.

    Please help me...

    Thank you

    RS

    I'm able to do. I used the formula below:

    COUNT (CASE WHEN "Status". ("Employment status" = 'Succeed' THEN 1 END)

    even for running status and on the other and it works very well...

  • -SQL - GROUP BY clause: fields of nonaggregate mandate

    Hello

    I study data (especially data recovery) and found something interesting.

    When you use an aggregate function in the SELECT clause, it is mandatory to have all fields that are not aggregated in the SELECT clause to be there in the GROUP BY clause.
    For example,.

    SELECT dept_no, Salary
    The EMPLOYEE
    GROUP BY dept_no;

    The SQL above works fine.
    But what happens if the user forgets the dept_no in the GROUP BY clause or the clause GROUP BY itself is missing?
    Certainly, it is a mistake.

    Why this error is not handled by the database. I mean, the database must be smart/pretty smart to add the GROUP BY clause by itself. So let's assume that, if I miss the GROUP BY clause or miss a field no aggregated from the SELECT clause when I get at least an aggregate function on a field with at least a no aggregated field in the SELECT clause, the database should check the GROUP BY clause at compile time and add mandate missed the fields in the GROUP BY clause.

    Example,

    SQL1:_
    SELECT dept_no, Salary
    The EMPLOYEE
    GROUP BY dept_no;

    SQL2:_
    SELECT dept_no, Salary
    The EMPLOYEE;

    Here, the SQL1 and SQL2, both should give me same output without error.

    I can't understand why this is handled?

    Hello

    998478 wrote:
    ... If we mix the aggregated and non-aggregated values, then there must be a GROUP BY clause that contains all non-aggregated values. Why this is handled by the database/compiler itself?

    It IS managed by the compiler itself. The compiler manages to trigger an error. The compiler has no way of knowing if you want to remove something from the SELECT clause, or add something to the GROUP BY clause, or not to use the aggregate functions or use several aggregate functions, or a combination of the above. If the compiler re-writes your code and none of these things done automatically, it would be wrong more often that he was right, and you would (rightly) complain about his behavior.

    For example, it is clearly wrong:

    SELECT    deptno
    ,       job
    ,       SUM (sal)
    FROM       scott.emp
    GROUP BY  deptno
    ;
    

    What is the right way to fix it?

    1. remove something from the SELECT clause

    SELECT    deptno
    ,       SUM (sal)
    FROM       scott.emp
    GROUP BY  deptno
    ;
    

    2. add something to the GROUP BY clause

    SELECT    deptno
    ,       job
    ,       SUM (sal)
    FROM       scott.emp
    GROUP BY  deptno
    ,         job
    ;
    

    3. do not use aggregate functions

    SELECT    deptno
    ,       job
    ,       sal
    FROM       scott.emp
    ;
    

    4. use several aggregate functions

    SELECT    deptno
    ,       MIN (job)
    ,       SUM (sal)
    FROM       scott.emp
    GROUP BY  deptno
    ;
    

    What are all the options, either. For example, the correct solution would be to use analytical functions instead of aggregate functions.
    How can anyone tell which of them is right? They all have the right answer for some problem.

    Moreover, by saying that everying in the SELECT clause must be an aggregate or in the GROUP BY clause is a bit oversimplified.
    Fuller, here's the ABC of GROUP BY:
    When you use a GROUP BY clause or in an aggregate function, then all in the SELECT clause must be:
    (A) a ggregate function,
    (B) one of the expressions "group By."
    (C) adding to C, or
    (D) something that Depends on the foregoing. (For example, if you "GROUP BY TRUNC (dt)", you can SELECT "TO_CHAR (TRUNC (dt), 'Mon - DD')").

    Published by: Frank Kulash on April 13, 2013 13:44
    Additional code examples.

  • Control the Append KM, Group by clause

    Hi all

    I am using the max function in interface (KM: control IKM append), in the map apart from the source columns in the data store that I use few variables ODI (say LD_ID = 200). Sort of variable LD_ID is being picked up by the KM in the group clause, why Labour fails with the error
    GROUP BY position 200 isn't in the target list. I understand the error but do not know why this variable in the grop is recovered by the clause. The substituition method that I see in the KM is odiRef.getGrpBy)

    Can someone help me with this please?

    Thank you
    Ashok

    Hey Ashok,

    When using (a) or several global functions, like SUM, ODI add one GROUP BY clause with all other columns in it.
    You can try to move the mapping of the LD_ID on the target and see if it works (it depends on the architecture you).

    Kind regards
    JeromeFr

  • Group by Clause displays all values search

    Hello friends

    I have a simple table with columns named Date, reason, product and County and the sample data are shown below.

    ==========================
    Date reason product count
    ==========================
    08/06/2012 raison1 home 1
    08/07/2012 raison2 motor 1
    08/08/2012 raison1 home 1
    08/09/2012 Reason3 Home 2
    08/10/2012 raison1 home 1
    08/06/2012 Reason5 home 1
    ===========================

    Altogether, I have 5 values of research through Reason5 raison1 reason, but few of them understand the table above.
    I would like to diplay result per day and I will quote an example of August 6, I want to display the result below, i.e. show all reason 5 search and assign zero count if there are no records for this day there.

    =====================================
    DATE REASON HOME_COUNT MOTOR_COUNT
    =====================================
    08/06/2012 raison1 1-0
    08/06/2012 0 1 raison2
    08/06/2012 Reason3 0 0
    08/06/2012 Reason4 0 0
    08/06/2012 Reason5 1 0
    =====================================


    If we write group by clause, missing for reasons such as Reason3 Reason4 will not appear in the result set.
    And I tried to write several UNION ALL queries to get the above result that works very well, but if it 100 search values, I don't want to write 100 Union queries.
    Please let me know if you have analytical functions to display the results of the end?

    Thank you
    Murali.

    Published by: Nathalie b on August 19, 2012 20:17

    If you followed relational design, you should lookup table. If you do not, you need to create a. In addition, date is reserved word, and the County is a key word, to not use as column names. Then, use the outer join:

    SQL> create table tbl as
      2  select to_date('06/08/2012','dd/mm/yyyy') dt,'Reason1' reason,'Home' product,1 qty from dual union all
      3  select to_date('07/08/2012','dd/mm/yyyy'),'Reason2','Motor',1 from dual union all
      4  select to_date('08/08/2012','dd/mm/yyyy'),'Reason1','Home',1 from dual union all
      5  select to_date('09/08/2012','dd/mm/yyyy'),'Reason3','Home',2 from dual union all
      6  select to_date('10/08/2012','dd/mm/yyyy'),'Reason1','Home',1 from dual union all
      7  select to_date('06/08/2012','dd/mm/yyyy'),'Reason5','Home',1 from dual
      8  /
    
    Table created.
    
    SQL> create table reason_list as
      2  select  'Reason' || level reason from dual connect by level <= 5
      3  /
    
    Table created.
    
    SQL> select  d.dt,
      2          r.reason,
      3          nvl(
      4              sum(
      5                  case product
      6                    when 'Home' then qty
      7                  end
      8                 ),
      9              0
     10             ) home_qty,
     11          nvl(
     12              sum(
     13                  case product
     14                    when 'Motor' then qty
     15                  end
     16                 ),
     17              0
     18             ) motor_qty
     19    from      (
     20               select  min_dt + level - 1 dt
     21                 from  (
     22                        select  min(dt) min_dt,
     23                                max(dt) max_dt
     24                          from  tbl
     25                       )
     26                 connect by level <= max_dt - min_dt + 1
     27              ) d
     28          cross join
     29              reason_list r
     30          left join
     31              tbl t
     32            on (
     33                    t.dt = d.dt
     34                and
     35                    t.reason = r.reason
     36               )
     37    group by d.dt,
     38             r.reason
     39    order by d.dt,
     40             r.reason
     41  /
    
    DT        REASON                                           HOME_QTY  MOTOR_QTY
    --------- ---------------------------------------------- ---------- ----------
    06-AUG-12 Reason1                                                 1          0
    06-AUG-12 Reason2                                                 0          0
    06-AUG-12 Reason3                                                 0          0
    06-AUG-12 Reason4                                                 0          0
    06-AUG-12 Reason5                                                 1          0
    07-AUG-12 Reason1                                                 0          0
    07-AUG-12 Reason2                                                 0          1
    07-AUG-12 Reason3                                                 0          0
    07-AUG-12 Reason4                                                 0          0
    07-AUG-12 Reason5                                                 0          0
    08-AUG-12 Reason1                                                 1          0
    
    DT        REASON                                           HOME_QTY  MOTOR_QTY
    --------- ---------------------------------------------- ---------- ----------
    08-AUG-12 Reason2                                                 0          0
    08-AUG-12 Reason3                                                 0          0
    08-AUG-12 Reason4                                                 0          0
    08-AUG-12 Reason5                                                 0          0
    09-AUG-12 Reason1                                                 0          0
    09-AUG-12 Reason2                                                 0          0
    09-AUG-12 Reason3                                                 2          0
    09-AUG-12 Reason4                                                 0          0
    09-AUG-12 Reason5                                                 0          0
    10-AUG-12 Reason1                                                 1          0
    10-AUG-12 Reason2                                                 0          0
    
    DT        REASON                                           HOME_QTY  MOTOR_QTY
    --------- ---------------------------------------------- ---------- ----------
    10-AUG-12 Reason3                                                 0          0
    10-AUG-12 Reason4                                                 0          0
    10-AUG-12 Reason5                                                 0          0
    
    25 rows selected.
    
    SQL> 
    

    SY.

  • Reg - search form for a VO in group by clause

    Hello
    I have a bar chart that displays data based on the query below.

    SELECT THE STATE. BATCH AS STATUSID, STATUS. STATUS, COUNTY (SR. SERVICEREQUEST_ID) AS SRCOUNT
    OF SR, SERVICEREQUESTSTATUS STATE SERVICE_REQUEST
    WHERE SR. BATCH = STATUS. BATCH
    GROUP STATUS. BATCH, STATUS. STATUS, SR. BATCH

    It displays the number of SRs against a particular status.
    Now, I need to add a search form to this graph with the customer and the date range.
    So you need to add the following line to the place where clause.
    SR. "CUSTOMER_ID =: customerId AND SR. "BETWEEN REQUESTED_ON: fromDate and: to this day.
    But the SR columns. CUSTOMER_ID, SR. REQUESTED_ON also needs to be added to the select clause to create criteria for the search panel view.
    The two columns should also be added to the group by clause if you want to add in the select clause.
    This would not produce the expected results.
    How to create a search with the criteria only form in the where clause. Help, please.


    With respect,
    Guna

    [Url http://docs.oracle.com/cd/E16162_01/apirefs.1112/e17483/oracle/jbo/server/ViewObjectImpl.html] ViewObjectImpl has methods to do this programmatically (setQuery, defineNamedWhereClauseParam, setNamedWhereClauseParam) that you can use to manipulate the query variables bind expected and the values of the lie.

    John

  • ORA-00907: lack the right parenthesis when using Group by clause with xmlagg

    I have the following query and I am getting ORA-00907 error when I use the clause with the xmlagg function group.
    select xmlelement("Mitigation",
                    xmlelement("m_szMethodName",tm.DisplayName),
                    xmlelement("SubstanceInterferenceProtocolList",
                                (select xmlagg(xmlelement("MitigationProtocol",
                                        xmlelement("m_szMethodName",tm.DisplayName),
                                        xmlelement("m_szInterferenceProtocolName",tmp.protocol_name),
                                        xmlelement("m_szInterferenceSubstance",tmp.intf_mtrl_prod_code),
                                        xmlelement("m_ProtocolParameters",
                                            xmlelement("m_szProtocolName",tmp.protocol_name),
                                                xmlelement("m_Consumables",
                                                    xmlelement("Consumable",
                                                        xmlelement("m_szConsumId", xrl.rgnt_pack_name),
                                                        xmlelement("m_szProductCode",xrl.pack_prod_code),
                                                        xmlelement("m_nVolume",tmp.fluid_vol),
                                                        xmlelement("m_szProtocolStep",xps.protocol_step_name))),
                                                    xmlelement("m_ProtParamList",
                                                        xmlagg(
                                                        xmlelement("ParameterValues",
                                                            xmlelement("m_szProtocolName",tmp.protocol_name),
                                                            xmlelement("m_Time",xpsd.parameter_ntime_value))
                                                        group by tmp.ccd_test_id,tmp.intf_mtrl_prod_code)
                    )))
                    order by tmp.ccd_test_id, tmp.intf_mtrl_prod_code, xps.protocol_step_intprotocolstep )
                    from XPR_tdef_mitigation_protocol tmp, xp_reagentlist xrl,
                    xpr_protocol_settings xps, xpr_protocol_settings_default xpsd
                    where tmp.ccd_test_id = tm.ccd_test_id
                    and tmp.ccd_test_id = xrl.ccd_test_id
                    and tmp.pack_prod_code = xrl.pack_prod_code
                    and tmp.intf_type = 1
                    and xps.protocol_name = xpsd.protocol_name
                    and xps.protocol_step_name = xpsd.protocol_step_name
                    and xps.ps_action_parameterlist = xpsd.ps_action_parameterlist
                    and xps.protocol_name =  tmp.PROTOCOL_NAME
                    )))
    from XPtoXPRTdef_defn_mapping tm
    where tm.DisplayName = 'SYPH'
    If I remove the clause xmlagg and the group by clause, the query works well and not give me the result.
    But in this code XML, the output format is incorrect for my application.

    Could someone help out here?

    Now my problem is that this unique coating is more than 32767 characters and utl_file can write 32767 bytes per line.
    Someone deal with this?

    Serialize the output as CLOB and DBMS_XSLPROCESSOR.clob2file procedure used to write to a file:

    DECLARE
      xml_output CLOB;
    BEGIN
      SELECT XMLElement("Department",
               XMLAgg(
                 XMLElement("Employee",e.job_id||' '||e.last_name)
                 ORDER BY e.last_name
               )
             ).getClobVal() AS "Dept_list"
      INTO xml_output
      FROM hr.employees e
      WHERE e.department_id = 30 OR e.department_id = 40;
    
      DBMS_XSLPROCESSOR.clob2file(xml_output, 'XML_DIR', 'test.xml');
    END;
    /
    
  • can do without group by clause report through parameter

    Hello expert,

    I need to create a report in which the user select a field and adds this field in the group by clause of the sql query.


    I know that the notion of setting lexical but getting only not the idea how the user for the group by clause...
    I tried the following

    Select trunc (m.spc_doc_date),
    -d.spc_item_code,
    Sum (NVL(d.req_qty,0)) x, sum (nvl(d.spc_item_qty,0)) y
    of spc_ppc_daily_m m, spc_ppc_daily_d d
    where m.spc_doc_ # in (select spc_doc_ # from spc_ppc_daily_m where fncl_year = 20112012)
    and m.fncl_year = 20112012
    and d.blce_qty > 0
    and m.spc_locn_code = 400001
    "and m.spc_doc_date between February 1, 2012'-February 29, 2012"
    and m.spc_locn_code = d.spc_locn_code
    and m.fncl_year = d.fncl_year
    and m.spc_doc_ #= d.spc_doc_ #.
    Group by & g_by
    ----------------------------

    g_by is the report parameter

    Thank you
    Yoann

    yash_08031983 wrote:
    Hello Hamid

    But when I compile my sql triggers Error statement due to & g_by or: g_by parameter.

    Hello, yoann

    Most likely, you are getting error ORA-00936 .

    If the error above is true, then you are missing a part in sql.
    First without lexical parameter your query should be ok. Correct your query without lexical parameter, and then add the lexical parameter.
    Try this

    select trunc(m.spc_doc_date),
    --d.spc_item_code,
    sum(nvl(d.req_qty,0)) x,sum(nvl(d.spc_item_qty,0)) y
    from spc_ppc_daily_m m, spc_ppc_daily_d d
    where m.spc_doc_# in(select spc_doc_# from spc_ppc_daily_m where fncl_year=20112012)
    and m.fncl_year=20112012
    and d.blce_qty>0
    and m.spc_locn_code=400001
    and m.spc_doc_date between '01-feb-2012' and '29-feb-2012'
    and m.spc_locn_code=d.spc_locn_code
    and m.fncl_year=d.fncl_year
    and m.spc_doc_#=d.spc_doc_#
    group by trunc(m.spc_doc_date) &g_by 
    

    Hope this helps...

  • Select the columns not in the group by clause

    Hello

    My version of DB is 10.0.2

    I have query, where in I need to select two columns more but that should not be part of the group by Clause.

    Does perform a work around?
    SELECT  F.custnum, 
      V.Import_date,
     -- F.ErledigtMM,F.ErledigtGrundMM, (Columns to be selected additionally)
      nvl(sum(nvl(round(V.VerAuf16/1000,2), 0)  +nvl(round(V.VerAuf17/1000,2), 0)  + nvl(round(V.VerAuf18/1000,2), 0)  + nvl(round(V.VerAuf19/1000,2), 0)  + nvl(round(V.VerAuf20/1000,2), 0)  + nvl(round(V.VerAufKAPUn/1000,2), 0)  + nvl(round(V.VerAufKAPVz/1000,2), 0) ), 0)  Mandantenforderung,
      nvl(sum(nvl(round(V.VerAuf4/1000,2), 0) ), 0) Inkassokosten,
      nvl(sum(nvl(round(V.VerAuf5/1000,2), 0) ), 0) KontoFuehrungsgebuehren,
      nvl(sum(nvl(round(V.VerAuf1/1000,2), 0)  + nvl(round(V.VerAuf2/1000,2), 0) ), 0)  Verwertungskosten,
      nvl(sum(nvl(round(V.VerAuf10/1000,2), 0)  + nvl(round(V.VerAuf8/1000,2), 0) + nvl(round(V.VerAuf9/1000,2), 0) ), 0)  Barauslagen,
      nvl(sum(nvl(round(V.VerAuf13/1000,2), 0)  + nvl(round(V.VerAuf14/1000,2), 0) + nvl(round(V.VerAuf15/1000,2), 0)  + nvl(round(V.VerAuf6/1000,2), 0) ),0)  Gerichtskosten,
      nvl(sum(nvl(round(V.VerAuf11/1000,2), 0)  + nvl(round(V.VerAuf12/1000,2), 0)  + nvl(round(V.VerAuf7/1000,2), 0) ), 0) RAKosten,
      TO_CHAR(F.Created_Date,'MM.YYYY') Created_Date_MM ,
      TO_CHAR(F.Created_Date,'YYYY') Created_Date_MMRRRR
    FROM FACM F, VA V 
       WHERE  F.custnum =  DECODE(0,0,F.custnum,0) AND
      F.accnum = V.accnum 
      GROUP BY F.custnum, V.Import_date,TO_CHAR(F.Created_Date,'MM.YYYY') ,TO_CHAR(F.Created_Date,'YYYY'))

    Hello

    Here's what I suggest:

    select
    a.custnum,
    a.import_date,
    b.ErledigtMM,
    b.ErledigtGrundMM,
    a.Mandantenforderung,
    a.Inkassokosten,
    a.KontoFuehrungsgebuehren,
    a.Verwertungskosten,
    a.Barauslagen,
    a.Gerichtskosten,
    a.RAKosten,
    a.Created_Date_MM ,
    a.Created_Date_MMRRRR
    from (
    SELECT  F.custnum,
      V.Import_date,
      nvl(sum(nvl(round(V.VerAuf16/1000,2), 0)  +nvl(round(V.VerAuf17/1000,2), 0)  + nvl(round(V.VerAuf18/1000,2), 0)  + nvl(round(V.VerAuf19/1000,2), 0)  + nvl(round(V.VerAuf20/1000,2), 0)  + nvl(round(V.VerAufKAPUn/1000,2), 0)  + nvl(round(V.VerAufKAPVz/1000,2), 0) ), 0)  Mandantenforderung,
      nvl(sum(nvl(round(V.VerAuf4/1000,2), 0) ), 0) Inkassokosten,
      nvl(sum(nvl(round(V.VerAuf5/1000,2), 0) ), 0) KontoFuehrungsgebuehren,
      nvl(sum(nvl(round(V.VerAuf1/1000,2), 0)  + nvl(round(V.VerAuf2/1000,2), 0) ), 0)  Verwertungskosten,
      nvl(sum(nvl(round(V.VerAuf10/1000,2), 0)  + nvl(round(V.VerAuf8/1000,2), 0) + nvl(round(V.VerAuf9/1000,2), 0) ), 0)  Barauslagen,
      nvl(sum(nvl(round(V.VerAuf13/1000,2), 0)  + nvl(round(V.VerAuf14/1000,2), 0) + nvl(round(V.VerAuf15/1000,2), 0)  + nvl(round(V.VerAuf6/1000,2), 0) ),0)  Gerichtskosten,
      nvl(sum(nvl(round(V.VerAuf11/1000,2), 0)  + nvl(round(V.VerAuf12/1000,2), 0)  + nvl(round(V.VerAuf7/1000,2), 0) ), 0) RAKosten,
      TO_CHAR(F.Created_Date,'MM.YYYY') Created_Date_MM ,
      TO_CHAR(F.Created_Date,'YYYY') Created_Date_MMRRRR
    FROM FACM F, VA V
       WHERE  F.custnum =  DECODE(0,0,F.custnum,0) AND
      F.accnum = V.accnum
      GROUP BY F.custnum, V.Import_date,TO_CHAR(F.Created_Date,'MM.YYYY') ,TO_CHAR(F.Created_Date,'YYYY'))
    ) a,
    FACM b
    where b.custnum = a.custnum 
    

    By the way

    WHERE  F.custnum =  DECODE(0,0,F.custnum,0) AND F.accnum = V.accnum
    

    can be translated into

    WHERE F.accnum = V.accnum
    

    because

    F.custnum =  DECODE(0,0,F.custnum,0)
    

    is always true
    because

    DECODE(0,0,F.custnum,0)
    

    means

    if 0=0 then F.custnum else 0
    

Maybe you are looking for