-SQL - GROUP BY clause: fields of nonaggregate mandate
HelloI 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.
Tags: Database
Similar Questions
-
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 tableAsk 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.
-
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
Yoannyash_08031983 wrote:
Hello HamidBut 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 thisselect 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...
-
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 theINSERT... SELECT
statement works on mostSELECT
uses I tried, if this statement was also aGROUP BY
clause, it does not work, delivering a "ORA-00979: not aGROUP 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 2SQL >
Keep in mind index THAT MATERIALIZE is undocumented.
SY.
-
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:17If 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.
-
CFQUERYPARAM tag does not work in the GROUP BY clause
I get an error whenever I put a CFQUERYPARAM tag in a GROUP BY clause. I saw on another forum, someone had a similar problem with the ORDER BY clause
Here's a sample of what might look like my code
Select x, y, z of ABC
Group of < cfqueryparam value = 'x' cfsqltype = "cf_sql_float" >
Here is the error I get.
Run database query error.
[Macromedia] [Oracle JDBC Driver] [Oracle] ORA-00979: not a GROUP BY expression
Any idea?Cachedwithin and cachedafter functions store the query results in the RAM of the server. This means that, even if it is cached, when you run it, you get the cached result instead of going to the database to run again. This increases the speed of course, but if the data is changed during the period of cover, you have accuracy problems.
It creates no memory problems. In the administrator you book a certain amount of memory for the query cache. If you exceed this amount, the last request to shoot the first query on, or something like that.
In regards to what you're trying to do on the binding of variables to your group by clause, this isn't what cfqueryparam has been designed for. It has been designed to
where clauses (where it =
or insert queries (insert in my values in the table (field) ())
and things like that.You try to use it for anything other than what it was designed for, which explains why it does not work for you.
-
Group By clause in oracle 10g need help
Hello
We have a requirement that get the AR details of aging at the customer level. I wrote the following query to retrieve the correct rows at the invoice level. But now I need calculate the sum of the amounts and I show you the invoice and customer level. Could you please help me how can I group by the client.
Here's the query I used
Select ps.org_id
sobbed. SET_OF_BOOKS_ID
sobbed. CHART_OF_ACCOUNTS_ID
gcc. Company of SEGMENT1
gcc. SEGMENT2 location
gcc. Department of SEGMENT3
gcc. SEGMENT4 account
gcc. Future_1 SEGMENT5
gcc. SEGMENT6 Future_2
gcc. SEGMENT7 Future_3
gcc. CONCATENATED_SEGMENTS gl_cc_concat_kff
ps.trx_number
ps.trx_date
ps.due_date
ps.invoice_currency_code
sob.currency_code SOB_Currency_Code
ps.class
ps.amount_due_original
, ps.amount_due_original * nvl (ps.exchange_rate, 1) acctd_amount_due_original
ps.amount_due_remaining
ps.acctd_amount_due_remaining
ps.status
ps.cust_trx_type_id
ps.customer_site_use_id
ps.customer_trx_id
ps.cash_receipt_id
ps.gl_date
rctlda. CODE_COMBINATION_ID
ps.customer_id
nvl (ATCM. ATTRIBUTE5, ps. CUSTOMER_ID) End_Customer_Id
rc.customer_number
rc2. CUSTOMER_NUMBER Brand_Cust_no
, round ((sysdate-ps.due_date))
of gl_sets_of_books ob
, hr_operating_units or
ar_payment_schedules_all ps
ra_customers rc
ra_cust_trx_line_gl_dist_all rctlda
gl_code_combinations_kfv gcc
ra_customer_trx_all ATCM
ra_customers rc2
where sob.set_of_books_id = ou.set_of_books_id
and ou.organization_id = ps.org_id
and ps.status = 'OP '.
and ps.org_id is not null
and ps. CUSTOMER_ID = rc. CUSTOMER_ID
and ps. CUSTOMER_TRX_ID = rctlda. CUSTOMER_TRX_ID
and rctlda. ACCOUNT_CLASS = "REC".
and rctlda.latest_rec_flag = 'Y '.
and rctlda. CODE_COMBINATION_ID = gcc. CODE_COMBINATION_ID
and ps. CUSTOMER_TRX_ID = ATCM. CUSTOMER_TRX_ID
and gcc. CODE_COMBINATION_ID = 39446
- and ps.trx_number = 1-15O0A8O'
- and rc. CUSTOMER_NUMBER = 1-10PA5KX'
and nvl (ATCM. ATTRIBUTE5, ps. CUSTOMER_ID) = rc2. CUSTOMER_ID
Could someone help me how to recover the same columns with sum (ps.amount_due_original) for each client. I tried to use the group by clause, but it gives to new level of the invoice.
But my req's for each customer the amount of the invoice must be added and it should give the total
Thank you
THEREIf you need to have the amount of the invoice for each customer may also need to check the
CUBE
http://download.Oracle.com/docs/CD/B28359_01/server.111/b28286/statements_10002.htm#sthref9448
and example here
http://download.Oracle.com/docs/CD/B28359_01/server.111/b28286/statements_10002.htm#i2066443and ROLLUP
http://download.Oracle.com/docs/CD/B28359_01/server.111/b28286/statements_10002.htm#sthref9445I couldn't keep up with all your SQL statement, or I could rewrite for you once again
Thank youPublished by: user9532576 on July 21, 2009 09:24
-
Concatenation of data with the GROUP BY clause
Hi again!
Following my previous thread...
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)".
-
Grouping on the field created with substr
I don't know how to get around this problem.
Here are the contents of the field, point, I need to group by. The name of the element is actually the string AFTER the 'Test' and BEFORE 'Hour '.
TestNodAHour-03
TestNodCHour-00
TestNodBHour-01
TestNodDHour-02
Thus, in the example above, the element names would be "NodA", "NodC', 'NodB', 'NodD '.
I need to enter charges for these items (i.e. the substrings) names and come up with totals, so I tried the following:
The report header now has the right name, but the data are actually get wrapped by long names - the names actually in the fields. Is there anyway to group by the substr? Or I approach this all wrong?SELECT SUBSTR ( item , 5 , 4 ) AS Item , COUNT(*) FROM table_name WHERE Item_Type = '666' GROUP BY item ORDER BY item
BradHello
When you assign a column alias in a query, you can use it in the ORDER BY clause, but nowhere else in the same query.
So, when you are referring to 'article' in the GROUP BY clause, referring to the column called point, not the called alias element.Using a column as an alias is confusing name. try to avoid this.
You can repeat the expression in the GROUP BY clause:
SELECT SUBSTR ( item , 5 , 4 ) AS Item , COUNT(*) FROM table_name WHERE Item_Type = '666' GROUP BY SUBSTR ( item , 5 , 4 ) ORDER BY item
or you can assign the alias in a subquery. Then, it can be used in the GROUP BY clause (or elsewhere) in the Super-requete:
WITH reduce_item AS ( SELECT SUBSTR ( item , 5 , 4 ) AS Item , FROM table_name WHERE Item_Type = '666' ) SELECT item , COUNT (*) FROM reduce_item GROUP BY item ORDER BY item
-
A question about the analytical function used with the GROUP BY clause in SHORT
Hi all
I created the following table named myenterprise
If I want to find which is the total sales by city? I'll run the following queryCITY STOREID MONTH_NAME TOTAL_SALES ---------- ---------- ---------- ---------------------- paris id1 January 1000 paris id1 March 7000 paris id1 April 2000 paris id2 November 2000 paris id3 January 5000 london id4 Janaury 3000 london id4 August 6000 london id5 September 500 london id5 November 1000
that works very well and produces the expected result, i.e.SELECT city, SUM(total_sales) AS TOTAL_SALES_PER_CITY FROM myenterprise GROUP BY city ORDER BY city, TOTAL_SALES_PER_CITY;
Now in one of my books SQL (Mastering Oracle SQL) I found another method by using the SUM, but this time as an analytic function. Here's what the method of the book suggests as an alternative to the problem:CITY TOTAL_SALES_PER_CITY ---------- ---------------------- london 10500 paris 17000
I know that the analytic functions are executed after the GROUP BY clause has been transformed completely and Unlike regular aggregate functions, they return their result for each line belonging to the partitions specified in the partition clause (if there is a defined partition clause).SELECT city, SUM(SUM(total_sales)) OVER (PARTITION BY city) AS TOTAL_SALES_PER_CITY FROM myenterprise GROUP BY city ORDER BY city, TOTAL_SALES_PER_CITY;
Now my problem is that I do not understand what we have to use two functions SUM? If we only use one only, i.e.
This generates the following error:SELECT city, SUM(total_sales) OVER (PARTITION BY city) AS TOTAL_SALES_PER_CITY FROM myenterprise GROUP BY city ORDER BY city, TOTAL_SALES_PER_CITY;
The error is generated for the line 2 column 11 which is, for the expression SUM (total_sales), well it's true that total_sales does not appear in the GROUP BY clause, but this should not be a problem, it has been used in an analytical function, so it is evaluated after the GROUP BY clause.Error starting at line 2 in command: SELECT city, SUM(total_sales) OVER (PARTITION BY city) AS TOTAL_SALES_PER_CITY FROM myenterprise GROUP BY city ORDER BY city, TOTAL_SALES_PER_CITY Error at Command Line:2 Column:11 Error report: SQL Error: ORA-00979: not a GROUP BY expression 00979. 00000 - "not a GROUP BY expression" *Cause: *Action:
So here's my question:
Why use SUM (SUM (total_sales)) instead of SUM (total_sales)?
Thanks in advance!
:)
In case you are interested, that's my definition of the table:
Edited by: dariyoosh on April 9, 2009 04:51DROP TABLE myenterprise; CREATE TABLE myenterprise( city VARCHAR2(10), storeid VARCHAR2(10), month_name VARCHAR2(10), total_sales NUMBER); INSERT INTO myenterprise(city, storeid, month_name, total_sales) VALUES ('paris', 'id1', 'January', 1000); INSERT INTO myenterprise(city, storeid, month_name, total_sales) VALUES ('paris', 'id1', 'March', 7000); INSERT INTO myenterprise(city, storeid, month_name, total_sales) VALUES ('paris', 'id1', 'April', 2000); INSERT INTO myenterprise(city, storeid, month_name, total_sales) VALUES ('paris', 'id2', 'November', 2000); INSERT INTO myenterprise(city, storeid, month_name, total_sales) VALUES ('paris', 'id3', 'January', 5000); INSERT INTO myenterprise(city, storeid, month_name, total_sales) VALUES ('london', 'id4', 'Janaury', 3000); INSERT INTO myenterprise(city, storeid, month_name, total_sales) VALUES ('london', 'id4', 'August', 6000); INSERT INTO myenterprise(city, storeid, month_name, total_sales) VALUES ('london', 'id5', 'September', 500); INSERT INTO myenterprise(city, storeid, month_name, total_sales) VALUES ('london', 'id5', 'November', 1000);
It is clear that thet Analytics is reduntant here...
You can even use AVG or any analytic function...SQL> SELECT city, 2 avg(SUM(total_sales)) OVER (PARTITION BY city) AS TOTAL_SALES_PER_CITY 3 FROM myenterprise 4 GROUP BY city 5 ORDER BY city, TOTAL_SALES_PER_CITY; CITY TOTAL_SALES_PER_CITY ---------- -------------------- london 10500 paris 17000
-
GROUP BY clause diff in Sybase and Oracle
Hello
I am migrating from Sybase to Oracle code and came across a strange problem which is widely known to others :)
In Sybase, you can use columns or calculations in SELECTION expressions that do not appear
in the GROUP BY clause from the query. As
SELECT order.custid, customer.name, MAX (payments)
-> IN the order, customer
-> WHERE order.custid = customer.custid
-> GROUP BY order.custid;
works fine but for SQL, we must add customer.name to the customer of the GROUP BY clause.
In the same spirit, here is my SQL query
INSERT INTO GTT_CTRT_recalc_proc
(id_fin_rec,
id_imnt,
id_instr_opn,
dt_instr_opn,
dt_opn,
dt_cls_loanet,
dt_prcss,
am_invst)
SELECT t1.id_fin_rec,
T1.id_imnt,
T1.id_instr_opn,
T1.dt_instr_opn,
T1.dt_opn,
NVL (t1.dt_cls_loanet, l_dt_to),
T1.dt_prcss,
Sum (T2.am_invst) + (0.123 * (1 - abs (sign (0 - SUM (t2.am_invst)))))
OF GTT_CTRT_TEMP_recalc_process t1, GTT_CTRT_TEMP_recalc_process t2
WHERE t2.id < = t1.id
AND t2.id_imnt = t1.id_imnt
AND t2.id_instr_opn = t1.id_instr_opn
AND t2.dt_instr_opn = t1.dt_instr_opn
T1.id_imnt GROUP,
T1.id_instr_opn,
T1.dt_instr_opn,
T1.dt_opn,
T1.dt_cls_loanet,
T1.dt_prcss;
Has no t1.id_fin_rec in GROUP BY it fails in SQL.
I know that if I add this column in GROUP BY, it will work fine, but told me to keep the feature because it is as the result before and after the addition of the column is different, of course.
If please guide me what we can do in this situation and should work around that?
Thank you
AashishUse the PARTITION MORE rtaher than GROUP BY
INSERT INTO GTT_CTRT_recalc_proc (id_fin_rec, id_imnt, id_instr_opn, dt_instr_opn, dt_opn, dt_cls_loanet, dt_prcss, am_invst) SELECT t1.id_fin_rec, t1.id_imnt, t1.id_instr_opn, t1.dt_instr_opn, t1.dt_opn, NVL(t1.dt_cls_loanet, l_dt_to), t1.dt_prcss, SUM(t2.am_invst) OVER(PARTITION BY t1.id_imnt, t1.id_instr_opn, t1.dt_instr_opn, t1.dt_opn, t1.dt_cls_loanet, t1.dt_prcss) + (0.123 * (1 - ABS(SIGN( 0 - SUM(t2.am_invst) OVER(PARTITION BY t1.id_imnt, t1.id_instr_opn, t1.dt_instr_opn, t1.dt_opn, t1.dt_cls_loanet, t1.dt_prcss))))) FROM GTT_CTRT_TEMP_recalc_process t1, GTT_CTRT_TEMP_recalc_process t2 WHERE t2.ID <= t1.ID AND t2.id_imnt = t1.id_imnt AND t2.id_instr_opn = t1.id_instr_opn AND t2.dt_instr_opn = t1.dt_instr_opn
-
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...
-
Hello
I need a SQL to retrieve the fields and another piece of land to show if it is a line or a header for the WebADI project.
Can someone provide me with this SQL if you have already worked on it?
Thank you and best regards,
Yuvraj
SELECT DISTINCT fap.application_short_name 'Application Short Name',
bib.User_Name "integrating user name."
BLB.user_name "name of the page layout."
bicb.interface_col_name "name of the field."
blbb.user_name 'investment. "
BLC. Default_value 'Default Value ',.
UPPER CASE (NVL (blc.default_type, 'NONE'))
WHEN 'NONE', THEN 'none'
WHEN "FORMULA", THEN "Formula".
WHEN 'CONSTANT' THEN 'constant '.
WHEN 'PARAMETER' THEN 'setting '.
WHEN 'SQL' THEN 'SQL '.
WHEN 'ENVIRONMENT' THEN 'environment '.
ANOTHER "UNKNOWN".
END
'The Type by default'
OF apps.fnd_application fap.
Apps.bne_integrators_vl bib,
Apps.bne_layouts_vl blb,
Apps.bne_layout_blocks_tl Boop,
Apps.bne_layout_cols blc,
Apps.bne_interface_cols_b bicb,
Apps.bne_components_b bcb,
Apps.bne_param_lists_b bplb,
Apps.bne_param_list_items bpli
WHERE 1 = 1
AND fap.application_id = bib.application_id
-bne_integrators_b | bne_layouts_b
AND bib.integrator_code = blb.integrator_code
AND bib.application_id = blb.integrator_app_id
-bne_layouts_b | bne_layout_blocks_b
AND blb.layout_code = blbb.layout_code
AND blb.application_id = blbb.application_id
-bne_layout_blocks_b | bne_layout_cols
AND blbb.layout_code = blc.layout_code
AND blbb.application_id = blc.application_id
AND blbb.block_id = blc.block_id
-bne_layout_cols | bne_interface_cols_b
AND blc.application_id = bicb.application_id
AND blc.interface_code = bicb.interface_code
AND blc.sequence_num = bicb.sequence_num
-bne_interface_cols_b | bne_components_b
AND bicb.application_id = bcb.application_id
AND bicb.val_component_code = bcb.component_code
-bne_components_b | bne_param_lists_b
AND bcb.param_list_code = bplb.param_list_code
-bne_param_lists_b | bne_param_list_items
AND bplb.param_list_code = bpli.param_list_code
AND blbb.language = 'en '.
AND fap.application_short_name = 'PA '.
ORDER BY 1, 2;
-
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
AshokHey 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 -
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
Maybe you are looking for
-
Ubuntu on Toshiba Satellite U940 - startup of: SSD
Hi guys,. I think buy Toshiba Satellite U940. The reason is that he a dimmable-up ultrabook so I'll buy 16 GB of ram and a 120 GB of msata SSD. I'm going to install ubuntu. But because I'm not sure that two important things, I would ask you first. 1.
-
Portege Z930 - upgrading to Windows 8 without dvd player
Hello Is it possible to upgrade to windows 8 without using an external dvd drive? Thanks to the image of the dvd or something? I tried to put the dvd files in a disk drive external hard usb, but it didn't work... is it possible to install it without
-
OfficeJet Pro 8500 leaking blue ink.
I'm trying to disassemble the printer to gain access to the rear of the cartridge that assembles. I'm unable to remove the side panel of the case. Advice or suggestions appreciated! If I find the leak at the back of the Assembly, is - this repairable
-
Problem printing with HP OFFICEJET PRO8500A PREMIUM
I have to print certain documents yesterday, disappeared for a few hours and pick up where I left off. When I went to print my document following that nothing happened. He entered in the queue of the printer but would not print and I don't have the
-
animations of Siri 9.2 iOS on iPhone glitch 6 Plus
Anyone else notice this? It's a bit annoying for eyes. Reminds me of Android. Use iPhone 6 Plus