Subquery in GROUP BY CLAUSE

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

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

Similar Messages

  • Adding subquery to query w/ Group By clause crashes

    Hello all! I am trying to add in the subquery to the statement below. The query works fine before I add in the subquery, but after adding the subquery it will time out. If I comment out the MIN(table1.EOD_DATE) and the Group By clause, the query works fine.
    I do not want to do this I need those two items. What am I missing here? Any ideas are appreciated, thanks!
    SELECT table1.FUND,
    table1.DEPT,
    table1.ORG,
    table1.ACCT,
    LPAD(table1.FUND,3,0)||LPAD(table1.DEPT,2,0)||LPAD(table1.ORG,4,0)||SUBSTR(table1.ACCT,1,2) acct_no,
    LPAD(table1.FUND,3,0)||LPAD(table1.DEPT,2,0)||LPAD(table1.ORG,4,0)||table1.ACCT acct_no1,
    table2.FUND,
    table2.DEPT,
    table2.ORG,
    table2.ACCT
    MIN(table1.EOD_DATE)
    FROM table1,
    table2
    WHERE table1.fund BETWEEN substr(:P_ACCT_FROM,0,3) AND substr(:P_ACCT_TO,0,3)
    ANDtable1.dept BETWEEN substr(:P_ACCT_FROM,4,2) AND substr(:P_ACCT_TO,4,2)
    ANDtable1.org BETWEEN substr(:P_ACCT_FROM,6,4) AND substr(:P_ACCT_TO,6,4)
    ANDtable1.acct BETWEEN substr(:P_ACCT_FROM,10,5) AND substr(:P_ACCT_TO,10,5)
    AND floor(table1.acct/10000) in (6,8)
    AND SUBSTR(table1.acct,3) != '000'
    ANDtable1.eod_date BETWEEN :p_from_date AND :p_to_date
    AND table2.fund (+)=table1.fund
    AND table2.dept (+)=table1.dept
    AND table2.org (+)=table1.org
    AND table2.acct (+)=table1.acct
    AND table2.type IN( 'PI','JE','PR','VD','VU','AC','AD')
    AND table2.po_no IN
    SELECT trans.po_no
    FROM table2 trans LEFT OUTER JOIN req ON trans.po_no = req.po_no
    WHERE (trans.po_no IS NULL OR (TO_CHAR(req.open_date,'YYYY')) = (TO_CHAR(:p_year,'FM9999')))
    GROUP BY table1.fund,
    table1.dept,
    table1.org,
    table1.acct,
    table2.fund,
    table2.dept,
    table2.org,
    table2.acct
    ORDER BY LPAD(table1.FUND,3,0)||LPAD(table1.DEPT,2,0)||LPAD(table1.ORG,4,0)||SUBSTR(table1.ACCT,1,2),
    LPAD(table1.FUND,3,0)||LPAD(table1.DEPT,2,0)||LPAD(table1.ORG,4,0)||table1.ACCT

    Some untested comments;
    AND floor(table1.acct/10000) in (6,8)
    AND SUBSTR(table1.acct,3) != '000'Can these two conditions be combined, ie is this the same as;
    AND (table1.acct LIKE '0006%' OR table1.acct LIKE '0008%')Ignoring the hard coded dates (assumed they where used for testing) you should avoid using implicit conversions and two digit years;
    AND trans.activity_date BETWEEN TO_CHAR('01-jan-2007', 'dd-mon-yyyy') AND TO_CHAR('01-feb-2007', 'dd-mon-yyyy')You can convert your parameters once rather than converting every row by making hte parameter match the column data type;
    AND (   trans.po_no IS NULL
         OR req.open_date BETWEEN TO_DATE('01-JAN-' || TO_CHAR(:p_year,'9999') || ' 00:00:00' ,'DD-MON-YYYY HH24:MI:SS')
                              AND TO_DATE('31-DEC-' || TO_CHAR(:p_year,'9999') || ' 23:59:59' ,'DD-MON-YYYY HH24:MI:SS')
        )

  • Dataytpe mismatch error in GROUP BY Clause

    I have a function(undergoing testing) which returns column values separated by comma. Since this function returns a huge number of values (track_id) which a varchar2 type can't store i've made the return type to be CLOB.
    CREATE OR REPLACE FUNCTION get_shp_no_list
    p_shp_nbr IN VARCHAR2
    ) RETURN clob
    AS
      type shp_list_type is table of shp_trkg_dtl.track_ID%type;
      v_shp shp_list_type;
      v_ship_list  CLOB; 
    BEGIN
         -- get all track_ids for the selected shp_nbr
         SELECT DISTINCT (track_id )
         BULK COLLECT INTO v_shp
         FROM shp_trkg_dtl
         WHERE shp_id = p_shp_nbr
         ORDER BY track_ID;
         FOR i IN v_shp.FIRST .. v_shp.LAST LOOP
             IF v_ship_list IS NULL THEN
                v_ship_list := v_shp(i);
             ELSE
                v_ship_list := v_ship_list || ',' || v_shp(i);
             END IF;
         END LOOP;     
         --return the track_id list
         RETURN v_ship_list;
    EXCEPTION
      WHEN OTHERS THEN
        RETURN NULL;
    END get_shp_no_list;
    /This function works fine when called as standalone. But when i use this function in a SELECT in a stored proc i am getting error. My query looks like
    SELECT .......
    FROM
    (SELECT sd.shp_id,get_shp_no_list(sd.shp_id) trackids,
    FROM shp_trkg_dtl sd
    WHERE sd.shp_id IN  ('LPNR0456T','LPNR0498Y','LPNG0471G','LPNG783H') source1
    INNER JOIN ........................
    Group By source1.trackids  -- -<font color="red"><b> line where error has occured</b></font>
    ERROR at line 15:
    ORA-00932: inconsistent datatypes: expected - got CLOBAny thoughts?

    Taken from the 10.2 manual:
    Restrictions on the GROUP BY Clause:
    This clause is subject to the following restrictions:
    You cannot specify LOB columns, nested tables, or varrays as part of expr.
    The expressions can be of any form except scalar subquery expressions.
    If the group_by_clause references any object type columns, then the query will not be parallelized.
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_10002.htm#i2065646

  • BUG?: Code Editor – Completion Insight  - Autogenerate GROUP BY clause

    With the “Autogenerate GROUP BY clause” enabled the following problem occurs:
    Coding an inline select in an aggregate query:
      SELECT   (SELECT   DEPARTMENT_NAME
                  FROM   departments d
                 WHERE   d.department_id = e.department_id) dep
            , JOB_ID
            , SUM (salary)
        FROM   employees e
    GROUP BY   department_id, job_idCode group-by-autogenerate transforms this from time to time into:
      SELECT   (SELECT   DEPARTMENT_NAME
                  FROM   departments d
                 WHERE   d.department_id = e.department_id) dep
                 , JOB_ID
                 , SUM (salary)
        FROM   employees e
        GROUP BY (SELECT   DEPARTMENT_NAME
                  FROM   departments d
                 WHERE   d.department_id = e.department_id), JOB_IDWhich results in:
    ORA-22818. 00000 - "subquery expressions not allowed here"
    *Cause:    An attempt was made to use a subquery expression where these
    are not supported.
    *Action:   Rewrite the statement without the subquery expression.
    when trying to run it.
    (version 2.1.0.6.3; build MAIN-63.73; Windows XP)

    Duplicate of
    2.1 EA1 - Auto Group By inserted when unwanted/expected

  • Group By clause is not working

    I have two columns Department and EmpName:
    Department EmpName
    Sales empname1
    Sales empname2
    Marketing empname3
    Development empname4
    Now I want to count the number of employees in every department..
    I want the output to be
    Department Total
    Sales 2
    Marketing 1
    Development 1
    I am retrieving names of the department through a subquery
    The query I am trying to execute is:
    SELECT Department, Employee FROM
    ( SELECT ...query from other table) AS Department, count( A.EmpName) AS Employee
    FROM Employer A, EmployeeInfo B
    WHERE (A.EmpID = B.EmpID AND A.EmpCategory like 'Category2')
    GROUP BY Department
    I know that you cannot group by using aliases and hence a little work around, but still the query isn't working...I appreciate any help!!!!
    Edited by: 968775 on Oct 31, 2012 12:53 PM
    Edited by: 968775 on Oct 31, 2012 12:54 PM

    Hi,
    Welcome to the forum!
    968775 wrote:
    The query I am trying to execute is:
    SELECT Department, Employee FROM
    ( SELECT ...query from other table) AS Department, count( A.EmpName) AS Employee
    FROM Employer A, EmployeeInfo B
    WHERE (A.EmpID = B.EmpID AND A.EmpCategory like 'Category2')
    GROUP BY DepartmentRemember the ABC's of GROUP BY:
    When you use a GROUP BY clause and/or an aggregate fucntion, then every item in the SELECT clause must be:
    (A) an <b>A</b>ggregate function,
    (B) one of the "group <b>B</b>y" expressions,
    (C) a <b>C</b>onstant, or
    (D) something that <b>D</b>epends entirely on the above. (For example, if you "GROUP BY TRUNC(dt)", you can "SELECT TO_CHAR (TRUNC(dt), 'Mon-DD')").
    In the query above, EMPOYEE is none of these. I think you meant COUNT ( employee).
    SELECT    Department
    ,         COUNT (Employee)   AS num_employees
    FROM      ...
    I know that you cannot group by usingalias name and hence a little work around, You can assign the alias in a sub-query, then use the alias in the GROUP BY clause, or anywhere else you want to, in a super-query.
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
    See the forum FAQ {message:id=9360002}
    You'll get better answers faster if you always supply this information whenever you post a question.

  • Group by clause will try to group the primay key's

    hi all,
    For my requiremments and to avoid the the subquery i am using join and group by clause in my sql query in oracle 10g r2 database.my question is if i put a primary column the group clause then oracle try to group the records?.
    i know if we use a primary key column in group by clause there is no grouping will occur.
    but i have doubt oracle will try to group ? because it will take some amount of time to achive?
    else due presense of primay key column in group by clause oracle won't try?
    Please advice ??

    My query return the records less then the min v_date(date datatype) column.
    i check this condition in having clause
    my old query is
    select emp_id,emp_name,voldate,volume,productivity
    from volume v1
    where v1.voldate<=(select min(v2.voldate) form volume v2 where v2.emp_id=1)
    and v1.emp_id=1
    i change it as
    select emp_id,emp_name,voldate,volume,productivity
    from volume v1,volume v2
    where v1.emp_id=v2.emp_id
    having v1.voldate<=min(v2. voldate)
    group by emp_id,emp_name,voldate,volume,productivity
    above the query's emp_id is primay key for volume table
    comparing both query's which one is the best while looking th response time.
    else any other alternative for both the queries.??

  • Subquery in the HAVING Clause

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

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

  • Why is the GROUP BY clause not working in my Query?

    Dear All,
    Below is the Query for a Summary Debtors Aged Analysis.
    The GROUP BY clause does not seem to be working.
    The Query returns all the unpaid invoices, instead of a single total row for each Customer.
    If a Customer X has 10 unpaid invoices, 10 rows are displayed - one for each invoice.
    I was expecting only 1 row for Customer X, 1 for Customer Y, etc.
    This is what GROUP BY is supposed to do, but it is not doing its work.
    What has gone wrong?
    Thanks
    Leon Lai
    Here's my Query:
    declare @taxdt datetime
    set @taxdt
    /*select 1 from jdt1 t0 where t0.TaxDate*/ = [%1]
    SELECT
    CASE
                 WHEN T0.Account = 1220101 THEN 'Prim Cust'
                 WHEN T0.Account = 1220102 THEN 'Fgn Cust'
                 WHEN T0.Account = 1220103 THEN 'Local Cust'
                 WHEN T0.Account = 1220104 THEN 'Staff Loan' 
                 WHEN T0.Account = 1220105 THEN 'Dep with TP'
                 WHEN T0.Account = 1220106 THEN 'Adv to Cust'
                 WHEN T0.Account = 1220108 THEN 'Sund Drs'
                 ELSE 'Error ! ! !'
    END AS 'Control A/c',
    T1.CardCode AS 'BP Code',
    T2.Notes2 AS 'BP Name',
    SUM ((T0.Debit - T0.Credit)) AS 'Orig. Rs',       
    SUM ((T0.BalDueDeb - T0.BalDueCred)) AS 'Bal. Rs',     
    ((SELECT SUM(T0.BalDueDeb) - Sum(T0.BalDueCred)
        WHERE DateDiff(mm, T0.TaxDate, @taxdt) = 1))    
        AS '1 Mth Ago' 
    /* Similarly for other age brackets*/
    FROM JDT1 T0
    INNER JOIN OCRD T1 ON T0.ShortName = T1.CardCode
    LEFT OUTER JOIN OCPR T2 ON T1.CardCode = T2.Cardcode
    LEFT OUTER JOIN OJDT T3 ON T0.TransID = T3.TransID
    LEFT OUTER JOIN OINV  T4 ON T3.TransID = T4.TransID
    LEFT OUTER JOIN ORIN  T5 ON T3.TransID = T5.TransID
    WHERE
    T1.CardType = 'C'
    and (Balance) != 0
    and (T0.BalDueDeb - T0.BalDueCred) != 0
    GROUP BY T0.Account, T1.CardCode, T2.Notes2, T0.TaxDate

    Dear Neetu,
    Thanks for your reply.
    This Query is a modification of the Query you posted in SAP B1 SQL TIPS & TRICKS
    http://wiki.sdn.sap.com/wiki/display/B1/SAPB1SQLB-FNDebtorsAgingReportbydate
    So, maybe instead of referring to my Query, let's refer to yours. It may be easier for you to understand me.
    Once I understand the problem, I can adapt your query to suit my requirements
    So, let's start with a clean slate:
    The Query you have posted is for a DETAILED Debtors Aging Report.
    This lists all outstanding invoices, and ages them in the Age Brackets.
    What I want is a SUMMARY Debtors Aging Report.
    This will give the total amount owed by each Customer, and this amount is broken down in the Age Bracket Columns
    There will be a single row listed for each customer, something like this:
    Customer     Total Due     Current      1 Mth          2 Mth         3 Mth  etc
    Alfred       500,000       300,000       200,000
    Charles      800,000                     100,000       300,000       400,000
    How can you modify your query to make it become a Summary Report (1 line for each customer even if he has many invoices)?
    Thanks
    Leon Lai
    Here's your code
    SELECT T1.CardCode, T1.CardName, T1.CreditLine, T0.RefDate, T0.Ref1 'Document Number',
         CASE  WHEN T0.TransType=13 THEN 'Invoice'
              WHEN T0.TransType=14 THEN 'Credit Note'
              WHEN T0.TransType=30 THEN 'Journal'
              WHEN T0.TransType=24 THEN 'Receipt'
              END AS 'Document Type',
         T0.DueDate, (T0.Debit- T0.Credit) 'Balance'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')<=-1),0) 'Future'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=0 and DateDiff(day, T0.DueDate,'[%1]')<=30),0) 'Current'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>30 and DateDiff(day, T0.DueDate,'[%1]')<=60),0) '31-60 Days'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>60 and DateDiff(day, T0.DueDate,'[%1]')<=90),0) '61-90 Days'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>90 and DateDiff(day, T0.DueDate,'[%1]')<=120),0) '91-120 Days'
         ,ISNULL((SELECT T0.Debit-T0.Credit WHERE DateDiff(day, T0.DueDate,'[%1]')>=121),0) '121+ Days'
    FROM JDT1 T0 INNER JOIN OCRD T1 ON T0.ShortName = T1.CardCode
    WHERE (T0.MthDate IS NULL OR T0.MthDate > [%1]) AND T0.RefDate <= [%1] AND T1.CardType = 'C'
    ORDER BY T1.CardCode, T0.DueDate, T0.Ref1

  • How to write a SQL Query without using group by clause

    Hi,
    Can anyone help me to find out if there is a approach to build a SQL Query without using group by clause.
    Please site an example if is it so,
    Regards

    I hope this example could illuminate danepc on is problem.
    CREATE or replace TYPE MY_ARRAY AS TABLE OF INTEGER
    CREATE OR REPLACE FUNCTION GET_ARR return my_array
    as
         arr my_array;
    begin
         arr := my_array();
         for i in 1..10 loop
              arr.extend;
              arr(i) := i mod 7;
         end loop;
         return arr;
    end;
    select column_value
    from table(get_arr)
    order by column_value;
    select column_value,count(*) occurences
    from table(get_arr)
    group by column_value
    order by column_value;And the output should be something like this:
    SQL> CREATE or replace TYPE MY_ARRAY AS TABLE OF INTEGER
      2  /
    Tipo creato.
    SQL>
    SQL> CREATE OR REPLACE FUNCTION GET_ARR return my_array
      2  as
      3   arr my_array;
      4  begin
      5   arr := my_array();
      6   for i in 1..10 loop
      7    arr.extend;
      8    arr(i) := i mod 7;
      9   end loop;
    10   return arr;
    11  end;
    12  /
    Funzione creata.
    SQL>
    SQL>
    SQL> select column_value
      2  from table(get_arr)
      3  order by column_value;
    COLUMN_VALUE
               0
               1
               1
               2
               2
               3
               3
               4
               5
               6
    Selezionate 10 righe.
    SQL>
    SQL> select column_value,count(*) occurences
      2  from table(get_arr)
      3  group by column_value
      4  order by column_value;
    COLUMN_VALUE OCCURENCES
               0          1
               1          2
               2          2
               3          2
               4          1
               5          1
               6          1
    Selezionate 7 righe.
    SQL> Bye Alessandro

  • How to use order by within Group by clause

    Hi All,
    I need a help as to how should i use the Order by clause so that the data should be in order with respect to one column, and at the same time whole data is grouped by some other column...like
    Select RaceNo,Venue,FP,BP from Race group by RaceNo
    Here I want to order by FP in ascending order for each group. When i am using it , whole order is changing.
    Can anybody suggest me how to use order by clause that would apply to each group of data.
    Thanks .

    order by clause should be used at the last in any query.......but in group by clause u can't use use that becoz u group according to column then no ordering is needed there......if u want to filter something then u can use having clause and later if u need to arrange then u can use order by clause.........
    i hope this eg.l gives u some clarification....
    e.g
    select deptno,count(empno)
    from dept
    group by deptno
    having count(empno) > 10
    order by deptno

  • Creation of view with clob column in select and group by clause.

    Hi,
    We are trying to migrate a view from sql server2005 to oracle 10g. It has clob column which is used in group by clause. How can the same be achived in oracle 10g.
    Below is the sql statament used in creating view aling with its datatypes.
    CREATE OR REPLACE FORCE VIEW "TEST" ("CONTENT_ID", "TITLE", "KEYWORDS", "CONTENT", "ISPOPUP", "CREATED", "SEARCHSTARTDATE", "SEARCHENDDATE", "HITS", "TYPE", "CREATEDBY", "UPDATED", "ISDISPLAYED", "UPDATEDBY", "AVERAGERATING", "VOTES") AS
      SELECT content_ec.content_id,
              content_ec.title,
              content_ec.keywords,
              content_ec.content content ,
              content_ec.ispopup,
              content_ec.created,
              content_ec.searchstartdate,
              content_ec.searchenddate,
            COUNT(contenttracker_ec.contenttracker_id) hits,
              contenttypes_ec.type,
              users_ec_1.username createdby,
              Backup_Latest.created updated,
              Backup_Latest.isdisplayed,
              users_ec_1.username updatedby,
              guideratings.averagerating,
              guideratings.votes
         FROM users_ec users_ec_1
                JOIN Backup_Latest
                 ON users_ec_1.USER_ID = Backup_Latest.USER_ID
                RIGHT JOIN content_ec
                JOIN contenttypes_ec
                 ON content_ec.contenttype_id = contenttypes_ec.contenttype_id
                 ON Backup_Latest.content_id = content_ec.content_id
                LEFT JOIN guideratings
                 ON content_ec.content_id = guideratings.content_id
                LEFT JOIN contenttracker_ec
                 ON content_ec.content_id = contenttracker_ec.content_id
                LEFT JOIN users_ec users_ec_2
                 ON content_ec.user_id = users_ec_2.USER_ID
         GROUP BY content_ec.content_id,
         content_ec.title,
         content_ec.keywords,
         to_char(content_ec.content) ,
         content_ec.ispopup,
         content_ec.created,
         content_ec.searchstartdate,
         content_ec.searchenddate,
         contenttypes_ec.type,
         users_ec_1.username,
         Backup_Latest.created,
         Backup_Latest.isdisplayed,
         users_ec_1.username,
         guideratings.averagerating,
         guideratings.votes;
    Column Name      Data TYpe
    CONTENT_ID     NUMBER(10,0)
    TITLE          VARCHAR2(50)
    KEYWORDS     VARCHAR2(100)
    CONTENT          CLOB
    ISPOPUP          NUMBER(1,0)
    CREATED          TIMESTAMP(6)
    SEARCHSTARTDATE     TIMESTAMP(6)
    SEARCHENDDATE     TIMESTAMP(6)
    HITS          NUMBER
    TYPE          VARCHAR2(50)
    CREATEDBY     VARCHAR2(20)
    UPDATED          TIMESTAMP(6)
    ISDISPLAYED     NUMBER(1,0)
    UPDATEDBY     VARCHAR2(20)
    AVERAGERATING     NUMBER
    VOTES          NUMBERAny help realyy appreciated.
    Thanks in advance
    Edited by: user512743 on Dec 10, 2008 10:46 PM

    Hello,
    Specifically, this should be asked in the
    ASP.Net MVC forum on forums.asp.net.
    Karl
    When you see answers and helpful posts, please click Vote As Helpful, Propose As Answer, and/or Mark As Answer.
    My Blog: Unlock PowerShell
    My Book: Windows PowerShell 2.0 Bible
    My E-mail: -join ('6F6C646B61726C40686F746D61696C2E636F6D'-split'(?<=\G.{2})'|%{if($_){[char][int]"0x$_"}})

  • -- SQL -- GROUP BY clause: non-aggregate fields mandate

    Hello,
    I was studying Databases, (particularly the retrieval of the data), and found something interesting.
    While using an Aggregate Function in the SELECT clause, it is mandatory to have all the non-aggregate fields in the SELECT clause to be there in the GROUP BY clause.
    For example,
    SELECT dept_no, SUM(salary)
    FROM employee
    GROUP BY dept_no;
    The above SQL works fine.
    But, what if the user misses the dept_no in the GROUP BY clause or he/she misses the GROUP BY clause itself?
    Certainly, it is an error.
    Why is this error not handled by the database. I mean, the database should be smart/intelligent enough to add the GROUP BY clause by itself. So suppose, if I miss out the GROUP BY clause or miss a non-aggregate field from the SELECT clause when I am having at least one aggregate function on a field with at least one non-aggregated field in the SELECT clause, the database should check the GROUP BY clause at time of compilation and add the mandate missed out fields in the GROUP BY clause.
    Example,
    SQL1:_
    SELECT dept_no, SUM(salary)
    FROM employee
    GROUP BY dept_no;
    SQL2:_
    SELECT dept_no, SUM(salary)
    FROM employee;
    Here, the SQL1 and SQL2, both should give me same outputs without an error.
    I am unable to understand why is this not handled?

    Hi,
    998478 wrote:
    ... If we mix aggregate and non-aggregate values then there must be a GROUP BY clause containing all the non-aggregate values. Why is this not handled by the database/compiler itself? It IS handled by the compiler itself. The compiler handles it by raising an error. The compiler has no way of knowing whether you want to remove something from the SELECT clause, or to add something to the GROUP BY clause, or not to use aggregate functions, or to use more aggregate functions, or some combination of the above. If the compiler re-wrote your code, and did any of these things automatically, it would be wrong more often than it was right, and you would (rightly) be complaining about its behavior.
    For example, this is clearly wrong:
    SELECT    deptno
    ,       job
    ,       SUM (sal)
    FROM       scott.emp
    GROUP BY  deptno
    ;What is the right way to fix it?
    <h3>1. Remove something from the SELECT clause</h3>
    SELECT    deptno
    ,       SUM (sal)
    FROM       scott.emp
    GROUP BY  deptno
    ;<h3>2. Add something to the GROUP BY clause</h3>
    SELECT    deptno
    ,       job
    ,       SUM (sal)
    FROM       scott.emp
    GROUP BY  deptno
    ,         job
    ;<h3>3. Not use aggregate functions</h3>
    SELECT    deptno
    ,       job
    ,       sal
    FROM       scott.emp
    ;<h3>4. Use more aggregate functions</h3>
    SELECT    deptno
    ,       MIN (job)
    ,       SUM (sal)
    FROM       scott.emp
    GROUP BY  deptno
    ;These aren't all the options, either. For example, the correct fix might be to use analytic functions instead of aggregate functions.
    How can anybody say which of these is right? All of them are the right answer for some problem.
    By the way, saying that everying in the SELECT clause must be an aggregate or in the GROUP BY clause is a bit over-simplified.
    More completely, here are the ABC's of GROUP BY:
    When you use a GROUP BY clause and/or an aggregate function, then everything in the SELECT clause must be:
    (A) an <b>A</b>ggregate function,
    (B) one of the "group <b>B</b>y" expressions,
    (C) a <b>C</b>onstant, or
    (D) something that <b>D</b>epends entirely on the above. (For example, if you "GROUP BY TRUNC(dt)", you can SELECT "TO_CHAR (TRUNC(dt), 'Mon-DD')").
    Edited by: Frank Kulash on Apr 13, 2013 1:44 PM
    Added code examples.

  • Problem with the query in group by clause

    hi, i have problem with group by clause, can some one please help me.
    select
    header_id,
    (select sum(nvl(dr,0) - nvl(cr ,0)) from temp_tab a1
    where
    a1.country=a.country
    and a1.source='AP'
    and a1.header_id=a.header_id) WHT,
    sum(dr),
    sum(cr) from temp_tab a
    group by header_id,
    (select sum(nvl(dr,0) - nvl(cr ,0)) from temp_tab a1
    where
    a1.country=a.country
    and a1.source='AP'
    and a1.header_id=a.header_id)
    select * from temp_tab
    drop table temp_tab
    create table temp_tab(header_id number ,line_num number, country varchar2(2),
    source varchar2(2), dr number, cr number,primary key(header_id,line_num));
    insert into temp_tab(header_id, line_num,country, source, dr,cr) values(1, 1,'NL','AP',100,20);
    insert into temp_tab(header_id, line_num,country, source, dr,cr) values(1, 2,'PO','AP',20,20);
    insert into temp_tab(header_id, line_num,country, source, dr,cr) values(1, 3,'NL','AP',70,20);
    insert into temp_tab(header_id, line_num,country, source, dr,cr) values(2, 1,'NL','PA',100,20);
    insert into temp_tab(header_id, line_num,country, source, dr,cr) values(2, 2,'NL','PA',100,20);
    insert into temp_tab(header_id, line_num,country, source, dr,cr) values(3, 1,'KR','PO',100,20);
    commit;
    Appreciate your help.
    Thanks,

    select header_id,
             (select sum(nvl(dr,0) - nvl(cr ,0)) from temp_tab a1
             where a1.country=a.country
             and a1.source='AP'
             and a1.header_id=a.header_id) WHT,
             sum(dr),
             sum(cr)
      from temp_tab a
    group by header_id
    ,countryIt's kinda hard to follow what your query does... maybe because I'm only at my second coffee..
    Edited by: Alex Nuijten on Oct 2, 2009 8:07 AM

  • How to set a group by clause in ODI interface?

    How to set a group by clause in ODI interface?

    In ODI, group by method will be triggered automatically when any one of your mapping contains aggregate functions.
    Thanks,
    Saravanan Rajavel

  • How to include case stmt in group by clause

    Hi i have a question,
    How do i include a case statement in the group by clause?
    For example:
    Select
    (case when x.ctry is null then y.ctry else x.ctry end) as coo,
    sum (x.in_amt)
    from
    tbl1 x,
    tbl2 y
    where
    x.id = y.id
    group by
    (case when x.ctry is null then y.ctry else x.ctry end)
    Assume, I have got millions of records in both the tables, then my guess is, the above query might take huge time to complete.
    Any alternate method to do this?

    cd/ wrote:
    To remove the expression from the GROUP BY clause. I didn't advocate any performance improvements, did I?No you didn't. And your advice can indeed remove the expression from the GROUP BY clause. But I'm still puzzled as to why that would be a goal in itself.
    Regards,
    Rob.

Maybe you are looking for

  • Error while deploying from NWDS

    Hi, i am getting the following error while trying to deploy a PAR file from NWDS through export. PAR upload failed:C:\Documents and settings\Trials\Trials.par Please check the userid and password. i cross checked the userid and password.both are corr

  • DVD from PE9 won't play in computer let alone another DVD player

    I produced a 7 minute video in HD. I can play it on my computer either as HD or at standard res from files produced via the "Computer:Export files..." on the Share menu. I need to produce a standard NTSC DVD and when I burn using the "Disc: Burn DVD.

  • Open PO item is not visible in MD04

    Dear Expert, We have one scenario that one PO contain 3 line item which having Open PO Qty. but for line item 20 we have completed open qty i.e.40 & PR is also there. but it is not showing in MD04 & Also not visible in MIGO while doing GR so please s

  • Itunes and quicktime installation flub

    I have used itunes for years as well as quicktime. for some reason i am unable to launch itunes after the latest upgrade installation and quicktime fails to install with this error :-3 coming up during this install. i don't kno what to do. please any

  • Working with version management and promotion management best practices BO 4.1

    Hi Experts I wondered if anybody knows if there is a document or something about best practices to work with the version management and promotion management in BO 4.1? Our Environment includes two servers. The first one is our development and test se