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')
)
Similar Messages
-
Incorrect warning when parsing query with group by clause
I am using SQL Developer 4.0.0.13.80 with JDK 1.7.0_51 x64 on Windows 8.1
I have the following SQL, which works perfectly:
select substr(to_char(tot_amount), 0, 1) as digit, count(*)
from transactions
where tot_amount <> 0
group by substr(to_char(tot_amount), 0, 1)
order by digit;
However, SQL Developer is yellow-underlining the first line, telling me that:
SELECT list is inconsistent with GROUP BY; amend GROUP BY clause to: substr(to_char(rep_tot_amount), 0, 1), substr(to_char(rep_tot_amount),
which is clearly wrong.
Message was edited by: JamHan
Added code formatting.Hello,
I also have found the same issue with the GROUP BY hint. Another problem I found is that the hint suggests to amend the GROUP BY members to add also constant values that are included in the SELECTed columns and whenever those constants include strings with spaces, it generates an invalid query. Normally, constant values won't affect grouping functions and as such they can be omitted from the GROUP BY members, but it seems SQL Dev thinks it differently.
For example, if you try the following query:
SELECT d.DNAME, sum(e.sal) amt, 'Total salary' report_title, 100 report_nr
FROM scott.emp e, scott.dept d
WHERE e.DEPTNO = d.DEPTNO
GROUP BY d.DNAME;
when you hover the mouse pointer on the yellow hint, a popup will show the following message:
SELECT list inconsistent with GROUP BY; amend GROUP BY clause to:
d.DNAME, 'Total, 100
If you click on the hint, it will amend the group by members to become:
GROUP BY d.DNAME, 'Total, 100;
that is clearly incorrect syntax. You may notice that after the change the yellow hint is still there, suggesting to amend further the GROUP BY members. If you click again on the hint, you will end with the following:
GROUP BY d.DNAME, 'Total, 100;
, 'Total, 100
and so on.
I am not sure if this behaviour was already known (Vadim??), but it would be nice if somebody could file a bug against it.
Finally when writing big queries with complex functions and constant columns, those yellow lines extend all over the select list and they are visually annoying, so I wonder if there is a way to disable the GROUP BY hint until it gets fixed.
Thanks for any suggestion,
Paolo -
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 -
In evaluating several query plans, I've discovered several sqlstop messages that read:
<groupBy preclustered="true" sqlstop="Cannot generate SQL for the 'group-by' clause because it is not equivalent to the relational GROUP BY clause" stable="true">
I've examined the XQuery code and find no group clause and I can't find a reference to this message in the documentation or by googling the text. I assume that the grouping is being done implicitly by ODSI since it is not in the XQuery source. I have tried restructuring the code to no avail.
My question is -- is this causing me a performance problem since the sql is not generated, and if so, what steps must I take in the xquery structure to avoid this issue.
Many thanks to anyone who can provide some insight into this.
Regards,
PBis this causing me a performance problem since the sql is not generatedMy question is - why are you asking this question? :) Do you have a performance problem? The "Best Practices" posted as an announcement in this forum might help. Otherwise engage customer support.
To answer your question - your xquery likely generates nested/hierarchical xml - and looks something like below - which can be implemented with a sql left-outer-join ordered by CUSTOMER_ID of the customer-table, and taking the rows returned and ... grouping by CUSTOMER_ID to eliminate the duplicate customer information. So there's your group-by. But you cannot write sql that has a left-outer join, and then a group-by on the left-hand side. So the group by is done in the engine. Since the results are already sorted, the group-by in the engine simply skips over the duplicates (i.e. it's basically free).
for $c in CUSTOMER()
where $c/LAST_NAME = $lastname
return
<CUSTOMER>
... $c/CUSTOMER_ID ... (: in a left-outer-join, the CUSTOMER_ID is duplicated for every ORDER :)
{ for $o in ORDER()
where $o/CUSTOMER_ID eq $c/CUSTOMER_ID
return
</CUSTOMER> -
Strange behavior in inner query with group by clause
Hi All,
I found a very strange behaviour with Inner query having a group by clause.
Please look the sample code
Select b,c,qty from (select a,b,c,sum(d) qty from tab_xyz group by b,c);
This query gives output by summing b,c wise. But when i run the inner query it gives error as "not a group by expression "
My question is - though the inner query is wrong, how is it possible that this query gives output.
it behaves like -
Select b,c,qty from (select b,c,sum(d) qty from tab_xyz group by b,c);
Is it a normal behaviour ?
If it is a normal behaviour, then how group by behaves inside a inner query.
Thanks !!This case I have tested already and it throws error.
But why the initial posted query is not throwing
error even the inner query is wrong.
In what way oracle behaves for the initial posted
query?what is the scenario that throws the error? is it at the time when you only run the inner query or the whole query? -
Hi all,
I am struggling with one query.So Just i am giving the example..
CREATE TABLE test(num NUMBER,val NUMBER,description VARCHAR2(100))
table having the following data
num val description
1 100 first
1 200 second
1 300 third
Now i want to take the sum and discription based on num field..
i should get like ==> 1 600 first
my query is...
SELECT SUM(val),description
FROM test
GROUP BY description
But it's giving all records.because description field is there in select statement..
I tried two cursors for this case..its o.k
But Is there any way instead of using two cursors.
Thanks,Not sure what you are trying to achieve here. For the same value of NUM (say 1), you have 3 different values of VAL & DESCRIPTION. Do you want to sum up the VAL values for a particular value of NUM? In that case, what will be the corresponding DESCRIPTION?
How did you arrive at the result --- 1 600 first
-- whereas the DESCRIPTION is different for the 3 VAL values? -
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.TaxDateDear 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,
RegardsI 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 -
Can u write the following query without using group by clause
select sp.sid, p.pid, p.name from product p, supp_prod sp
where sp.pid= p.pid and
sp.sid = ( select sid from supp_prod group by sid
having count(*) =(select count(*) from product));
thru this, we retrieving all the products delivered by the supplier.
Can you write the following query without using the group by clauseselect sp.sid, p.pid, p.name
from product p, supp_prod sp
where sp.pid= p.pid the above query will still retrieve all the products supplied by the supplier. sub-query is not necessary.
maybe if you can post some sample data and output will help us understand what you want to achieve. -
Changing DEFAULT_WHERE of a FROM CLAUSE Query (with group by)
I have a Data Block of type FROM CLAUSE Query.
The Data Source Name is
SELECT A2.NAME,A2.EMPLOYEEID,A1.ORGID,A1.FSCLYEARID,A1.STATUS,COUNT(*) AS COUNTER
FROM S_PLC10300 A1,S_PLC50200 A2
WHERE A1.EMPLOYEEID=A2.EMPLOYEEID
GROUP BY A1.ORGID,A1.FSCLYEARID,A1.STATUS,A1.EMPLOYEEID,A2.NAME,A2.EMPLOYEEID
I have a Query Area with text items which i use to change the DEFAULT_WHERE Property.
My problem is that i can' t put in the DEFAULT_WHERE a field that doesn't belong to the SELECT Clause. Is there a way to achieve this?
Maybe changing the whole Data Source Name at runtime ?
ThanksAs I said i have a block with FROM clause query:
SELECT A1.ORGID,A1.FSCLYEARID,A1.STATUS, A1.EMPLOYEEID, A2.NAME,A2.EMPLOYEEID
FROM S_PLC10300 A1,S_PLC50200 A2
WHERE A1.EMPLOYEEID=A2.EMPLOYEEID
GROUP BY A1.ORGID,A1.FSCLYEARID,A1.STATUS,A1.EMPLOYEEID,A2.NAME,A2.EMPLOYEEID
i use the following code:
set_block_property(BLOCK,DEFAULT_WHERE,'A1.TRNSDATE>=:QUERY_BLOCK.TRNDATE);
What i think the code will do is change the FROM Clause Query to:
SELECT ... WHERE A1.EMPLOYEEID=A2.EMPLOYEEID AND A1.TRNSDATE>=:QUERY_BLOCK.TRNDATE
GROUP BY ...
A1.TRNSDATE is a valid field of table A1.
I can' t add TRNSDATE to my SELECT clause because i will have to add it to the GROUP BY clause.
Hope i made more sense this time.
Thanks -
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.) -
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 -
Columns not to be included in group by clause
I have a select query where i need to display count of records group by state_name
In my main select query i need to include two more columns which are not be included in group by clause so that the number of records displayed does not increase
I need to pass all these values from front end application so that i get count of records only by statename
But when i include these two columns in my select query my query is throwing an error bcoz i have not included them in my group by
How can we prevent this by not adding it to group by clauseOne general approach is (using the emp dept example)
I want
deptno dname, count(distinct empno)
I can do that
select d.deptno, d.dname, count(distinct e.empno)
from dept d, emp e
where e.deptno=d.deptno
group by d.deptno, d.dname;
or
select d.deptno, d.dname, count_emp
from dept d,
(select e.deptno, count(distinct empno)
from emp e
group by e.deptno
where d.deptno = e.deptno
or depending on version (you don't mention versionk, though most questions have version dependent answers)
select deptno
, dname
, (select count(distinct empno) from emp e where e.deptno=d.deptno)
from dept d
Obviously you can also use the FIRST and the LAST function to avoid having to include a column in the GROUP BY clause.
Sybrand Bakker
Senior Oracle DBA -
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 PMHi,
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.
Maybe you are looking for
-
Unable to access/lan2lan ping from VPN Fortigate to Cisco ASA 5505
Problem : Unable to access user A to user B User A --- router A (122, fortigate 80c) --- (Site to Site VPN between fortigate & cisco asa) --- router B (93, cisco Asa 5505{in front asa got cisco800[81] before to internet} ) --- User B After using wiz
-
Workitem button is not comming in swel though the workflow gets triggered
Dear All, I have copied the std wf WS20000075 and doing customization for po release as per my clients requirement. Once PO is being created in ME21N i am able to see the event trace in SWEL , but its showing an error , " Import container contains er
-
QuickTime Movies Playback Chokes
Yesterday, I made a big presentation in front of our entire company. My Keynote presentation had three embedded QuickTime clips. They were about 2-3 minutes each. I had run the presentation back at the office several times without problems. However,
-
Managing Thousands of Images II
I'm still new to Aperture, though I've read through the tutorial and played with it a bit. I'm going to be working with thousands of images of plants and animals associated with a particular website and would like to figure out how to manage them. I'
-
Sun recommended Java EE project directory structure?
Hello, It's said that there's a Java EE project directory structure recommended by Sun. How to get it? I find a link as following, http://java.sun.com/blueprints/code/projectconventions.html The article is my want? Thanks! a cup of Java, cheers! Sha