Aggregate Functionality
I have a requirement. First let me explain briefly the data we have:
1. There is an org heirarchy and we have around 8000 employees and every employee reports to 1 supervisor on a given day
2. An Employee can be tied to a transaction on a given day
3. A transaction can be of multiple types. We can expect arounf 40K transactiosn per day.
4. Data for every transaction ocurring in a day (assigned to one employee) is captured incrementally in a table.
Here is our initial reporting requirement:
1. User can go to the UI and provide a date range and also enter an employee number. The output shuld be the aggregate of all transactions that ocurred during the period selected. User can at the most give 3 months period to request the aggregates. his date can range from 1 day to 90 days. But the base table will have more than 5 years of data.
Question - since we dont know the number of days thta might be given as input, is there any way we can pre cumpute the aggregates and store in table or MV using rollup or cube functions. I am trying to avoid compuing it dynamically because it might take time to display the output in the reports. I hope I explianed the requirement better.
Why you can't use partitioning tables by month? last 3-4 partitions would be used in that query
Similar Messages
-
Trying to create a Histogram type/object for aggregate functions
Hi,
I am trying to create an aggregate function that will return a histogram
type.
It doesn't have to be an object that is returned, I don't mind returning
a string but I would like to keep the associative array (or something
else indexed by varchar2) as a static variable between iterations.
I started out with the SecondMax example in
http://www.csis.gvsu.edu/GeneralInfo/Oracle/appdev.920/a96595/dci11agg.htm#1004821
But even seems that even a simpler aggregate function like one strCat
below (which works) has problems because I get multiple permutations for
every combination. The natural way to solve this would be to create an
associative array as a static variable as part of the Histogram (see
code below). However, apparently Oracle refuses to accept associate
arrays in this context (PLS-00355 use of pl/sql table not allowed in
this context).
If there is no easy way to do the histogram quickly can we at least get
something like strCat to work in a specific order with a "partition by
... order by clause"? It seems that even with "PARALLEL_ENABLE"
commented out strCat still calls merge for function calls like:
select hr,qtr, count(tzrwy) rwys,
noam.strCat(cnt) rwycnt,
noam.strCat(tzrwy) config,
sum(cnt) cnt, min(minscore) minscore, max(maxscore) maxscore from
ordrwys group by hr,qtr
Not only does this create duplicate entries in the query result like
"A,B,C" and "A,C,B" it seems that the order in rwycnt and config are not
always the same so a user can not match the results based on their
order.
The difference between my functions and functions like sum and the
secondMax demonstrated in the documentation is that secondMax does not
care about the order in which it gets its arguments and does not need to
maintain an ordered set in order to return the correct results. A good
example of a built in oracle function that does care about all its
arguments and probably has to maintain a similar data structure to the
one I want is the PERCTILE_DISC function. If you can find the code for
that function (or something like it) and forward a reference to me that
in itself would be very helpful.
Thanks,
K.Dingle
CREATE OR REPLACE type Histogram as object
-- TYPE Hist10 IS TABLE OF pls_integer INDEX BY varchar2(10),
-- retval hist10;
-- retval number,
retval noam.const.hist10,
static function ODCIAggregateInitialize (sctx IN OUT Histogram)
return number,
member function ODCIAggregateIterate (self IN OUT Histogram,
value IN varchar2) return number,
member function ODCIAggregateTerminate (self IN Histogram,
returnValue OUT varchar2,
flags IN number) return number,
member function ODCIAggregateMerge (self IN OUT Histogram,
ctx2 IN Histogram) return number
CREATE OR REPLACE type body Histogram is
static function ODCIAggregateInitialize(sctx IN OUT Histogram) return
number is
begin
sctx := const.Hist10();
return ODCIConst.Success;
end;
member function ODCIAggregateIterate(self IN OUT Histogram, value IN
varchar2)
return number is
begin
if self.retval.exist(value)
then self.retval(value):=self.retval(value)+1;
else self.retval(value):=1;
end if;
return ODCIConst.Success;
end;
member function ODCIAggregateTerminate(self IN Histogram,
returnValue OUT varchar2,
flags IN number)
return number is
begin
returnValue := self.retval;
return ODCIConst.Success;
end;
member function ODCIAggregateMerge(self IN OUT Histogram,
ctx2 IN Histogram) return number is
begin
i := ctx2.FIRST; -- get subscript of first element
WHILE i IS NOT NULL LOOP
if self.retval.exist(ctx2(i))
then self.retval(i):=self.retval(i)+ctx2.retval(i);
else self.retval(value):=ctx2.retval(i);
end if;
i := ctx2.NEXT(i); -- get subscript of next element
END LOOP;
return ODCIConst.Success;
end;
end;
CREATE OR REPLACE type stringCat as object
retval varchar2(16383), -- concat of all value to now varchar2, --
highest value seen so far
static function ODCIAggregateInitialize (sctx IN OUT stringCat)
return number,
member function ODCIAggregateIterate (self IN OUT stringCat,
value IN varchar2) return number,
member function ODCIAggregateTerminate (self IN stringCat,
returnValue OUT varchar2,
flags IN number) return number,
member function ODCIAggregateMerge (self IN OUT stringCat,
ctx2 IN stringCat) return number
CREATE OR REPLACE type body stringCat is
static function ODCIAggregateInitialize(sctx IN OUT stringCat) return
number is
begin
sctx := stringCat('');
return ODCIConst.Success;
end;
member function ODCIAggregateIterate(self IN OUT stringCat, value IN
varchar2)
return number is
begin
if self.retval is null
then self.retval:=value;
else self.retval:=self.retval || ',' || value;
end if;
return ODCIConst.Success;
end;
member function ODCIAggregateTerminate(self IN stringCat,
returnValue OUT varchar2,
flags IN number)
return number is
begin
returnValue := self.retval;
return ODCIConst.Success;
end;
member function ODCIAggregateMerge(self IN OUT stringCat,
ctx2 IN stringCat) return number is
begin
self.retval := self.retval || ctx2.retval;
return ODCIConst.Success;
end;
end;
CREATE OR REPLACE FUNCTION StrCat (input varchar2) RETURN varchar2
-- PARALLEL_ENABLE
AGGREGATE USING StringCat;GraphicsConfiguration is an abstract class. You would need to subclass it. From the line of code you posted, it seems like you are going about things the wrong way. What are you trying to accomplish? Shouldn't this question be posted in the Swing or AWT forum?
-
Error in using aggregate function in Outer Query in Siebel Analytics
Hi,
When I am using aggregate function in outer query in Siebel Analytics I am facing error.
Error Codes: OPR4ONWY:U9IM8TAC:OI2DL65P:OI2DL65P
State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 59111] The SQL statement must include a GROUP BY clause. (HY000)
Bellow is the code.
SELECT test1.username saw_0, test1.desg saw_1,COUNT (test2.querydate) saw_2
FROM (SELECT POSITION.CBL username,
POSITION.CBP desg
FROM "CM"
WHERE (POSITION.BPTCD = 'Marketing')
AND (POSITION.EDate =TIMESTAMP '1899-01-01 00:00:00'
) test1,
(SELECT users.UN username,
measures."Query Count" querycount,
measures."Max Total Time" secs,
topic.db dashboardname,
"Query Time".DATE querydate
FROM "Plan"
WHERE (topic."Dashboard Name" IN ('DS'))) test2
WHERE test2.username = LOWER (test1.username)
AND test2.dashboardname = 'DS'
GROUP BY test1.username, test1.desgShould your query be a valid SQL query?
I can't think that the query you have would be valid in a SQL plus window.
Chris -
EJB 3.0: EJBQL aggregate functions not working properly
Hi!
We are experiencing problems when using aggregate functions within EJBQL queries. In my case, we have to use max() function to retrieve the max start_date from a specific table. In order to do this, we wrote the following code:
String strQuery = "select max(o.dt_fim) from Questionario o";
Query queryTeste = em.createQuery(strQuery);
List x = queryTeste.getResultList();
OBS: dt_fim is an Oracle 10g datetime column, with its corresponding entity attribute in Questionario entity class.
AFAIK, the query above should return only one record (object instance) containing the date value, right? However, it brougth a list of the entity objects, corresponding to all records in the table, as we had just run "select o from Questionario o".
Examining the server log we can see this behavior:
[TopLink Fine]:2006.09.12 01:47:55.526--
ServerSession(7119662)--Connection(7048401)--Thread(Thread[ApplicationServerThread-0,5,RequestThreadGroup])
--SELECT ID_QUEST, DT_INICIO, DT_FIM, DS_QUEST, DT_CRIACAO, TP_QUEST, NM_QUEST, COD_SEGMENTO, ID_GRUPO FROM TBBOP_QUEST
Are anyone experiencing this issue?
Is there any workaround?
Any help would be much appreciated, since we need to deploy the application for user testing asap.
Thanks in advance.
Best regards,
Gustavo
PS: We are using JDeveloper 10.1.3.0.4(SU4)
Message was edited by:
Gustavo Lopes SobralThe 10.1.3.0 versions of JDeveloper contain our early preview of EJB 3.0 JPA functionality. One limitation is that the query language is not complete (released before the spec was finalized).
You can use TopLink Essentials (JPA Reference implementation) whihc contains a complete compliant implementation of the final specification.
http://otn.oracle.com/jpa
The 10.1.3.1 JDeveloper preview ships with TopLink Essentials.
Doug -
Pivot table in BI Publisher: Different aggregate functions in data columns
Hi, everyone!
I`ve got some troubles with pivot table in my rtf-template.
Here is my xml:
<ROWSET>
<ROW>
<_BI_SUBRF_MO_._MUN_NAME_>МО Петроградский р-н</_BI_SUBRF_MO_._MUN_NAME_>
<_BI_PERS_ACCOUNT_CARD_._BI_PAC_NMB_>714000003</_BI_PERS_ACCOUNT_CARD_._BI_PAC_NMB_>
<_BI_MONTH_DEBET_._BI_DEBET_SUM_>0.0</_BI_MONTH_DEBET_._BI_DEBET_SUM_>
<_BI_CALENDAR_._YEAR__>2009</_BI_CALENDAR_._YEAR__>
<_BI_CALENDAR_._MONTH__>8</_BI_CALENDAR_._MONTH__>
</ROW>
<ROW>
<_BI_SUBRF_MO_._MUN_NAME_>МО Петроградский р-н</_BI_SUBRF_MO_._MUN_NAME_>
<_BI_PERS_ACCOUNT_CARD_._BI_PAC_NMB_>714000004</_BI_PERS_ACCOUNT_CARD_._BI_PAC_NMB_>
<_BI_MONTH_DEBET_._BI_DEBET_SUM_>165.58</_BI_MONTH_DEBET_._BI_DEBET_SUM_>
<_BI_CALENDAR_._YEAR__>2009</_BI_CALENDAR_._YEAR__>
<_BI_CALENDAR_._MONTH__>7</_BI_CALENDAR_._MONTH__>
</ROW>
<ROW>
<_BI_SUBRF_MO_._MUN_NAME_>МО Петроградский р-н</_BI_SUBRF_MO_._MUN_NAME_>
<_BI_PERS_ACCOUNT_CARD_._BI_PAC_NMB_>714000004</_BI_PERS_ACCOUNT_CARD_._BI_PAC_NMB_>
<_BI_MONTH_DEBET_._BI_DEBET_SUM_>165.58</_BI_MONTH_DEBET_._BI_DEBET_SUM_>
<_BI_CALENDAR_._YEAR__>2009</_BI_CALENDAR_._YEAR__>
<_BI_CALENDAR_._MONTH__>7</_BI_CALENDAR_._MONTH__>
</ROW>
...... and so on..
</ROWSET>
In the pivot table i`d like to see one row for every BISUBRF_MO_._MUN_NAME_ using BICALENDAR_._YEAR__ and BICALENDAR_._MONTH__ as measures and sum of BIMONTH_DEBET_._BI_DEBET_SUM_ and count of unique (or at least just count of) BIPERS_ACCOUNT_CARD_._BI_PAC_NMB_ in cells.
I create a pivot table using wizard, everything ok except one thing: as i understand, in pivot table for data in rows we can use only one kind of aggregate function e.g. only sum or only count.
Is there any way to use different aggregate functions in data cells?
Thank youAs you can see, when we use crosstab tag we can specify only one aggregate function for data cells.
Is there any way to get in XSL-FO (where we can what really happens) instead of:
<T1>
<xsl:value-of select="sum(current-group()/_BI_PERS_ACCOUNT_CARD_._BI_PAC_UNID_)"/>
</T1>
<T2>
<xsl:value-of select="sum(current-group()/_BI_MONTH_DEBET_._BI_DEBET_SUM_)"/>
</T2>
this
<T1>
<xsl:value-of select="sum(current-group()/_BI_PERS_ACCOUNT_CARD_._BI_PAC_UNID_)"/>
</T1>
<T2>
<xsl:value-of select="count(current-group()/_BI_MONTH_DEBET_._BI_DEBET_SUM_)"/>
</T2>
Edited by: user12115038 on 26.10.2009 8:08 -
Issue in pivot while using aggregate functions
when I use this below query in oracle sql developer
------------->select sum(round(8.08/0.54,2)*30) from dual.
i am getting result as 448.8.it is a correct value
but i use this below queries in pivot as same like above query i am getting result of doubled value 914.4.
PIVOT
SUM(round(ROUND(sellout,2)/6,2)) AS LAST_6_MON_SELL_OUT,
SUM(ROUND(inventory,2)) AS INVENTORY_INTINS_1,
Sum(round(ROUND(inventory,2)/round(ROUND(sellout,2)/6,2),2)*30) As Stockperday
FOR PRODUCT IN (56,78)
actually i am getting value for SUM(round(ROUND(sellout,2)/6,2)) is 0.54,*SUM(ROUND(inventory,2))* is 8.08 i the above query ,but i am getting wrong value for this aggregate function Sum(round(ROUND(inventory,2)/round(ROUND(sellout,2)/6,2),2)30)* as 914.4.but actual value is 448.8
why this problem.can anybody explain me.why this problemTry ur luck in 'sql plsql thread'
PL/SQL -
Why doesn't PIVOT clause work with COLLECT aggregate function in 11g ?
Hello all !
I am really puzzled as to what is considered an aggregate function in the context of the PIVOT clause in 11g.
I have been toying with quite a few things related to collections lately and this arose as an aside :
CREATE TABLE TEST_COLL
NODE_ID VARCHAR2(15 CHAR) NOT NULL,
NODE_VALUE VARCHAR2(45 CHAR) NOT NULL,
NODE_LEVEL NUMBER(1) NOT NULL
CREATE OR REPLACE TYPE TREE_NODE AS OBJECT
NODE_KEY VARCHAR2( 15 CHAR),
NODE_NAME VARCHAR2(127 CHAR)
CREATE OR REPLACE TYPE TREE_NODES AS TABLE OF TREE_NODE NOT NULL;At this stage I am sure we all agree that the query
SELECT NODE_LEVEL,
CAST(COLLECT(TREE_NODE(NODE_ID, NODE_VALUE)) AS TREE_NODES) AS NODES
FROM TEST_COLL
GROUP BY NODE_LEVEL;is perfectly valid as the COLLECT function is an aggregate function according to the [Official Documentation|http://docs.oracle.com/cd/E11882_01/server.112/e10592/functions031.htm#i1271564]
But then, one of the following two queries should work
SELECT CAST(REGION_NODES AS TREE_NODES) AS REGIONS,
CAST(DEPARTMENT_NODES AS TREE_NODES) AS DEPARTMENTS,
CAST(AREA_NODES AS TREE_NODES) AS AREAS,
CAST(CENTRE_NODES AS TREE_NODES) AS CENTRES
FROM (SELECT NODE_LEVEL, TREE_NODE(NODE_ID, NODE_VALUE) AS NODE
FROM TREE_COLL
PIVOT (COLLECT(NODE) FOR NODE_LEVEL IN (1 AS REGION_NODES,
2 AS DEPARTMENT_NODES,
3 AS AREA_NODES,
4 AS CENTRE_NODES
or (better)
SELECT REGION_NODES AS REGIONS,
DEPARTMENT_NODES AS DEPARTMENTS,
AREA_NODES AS AREAS,
CENTRE_NODES AS CENTRES
FROM (SELECT NODE_LEVEL, TREE_NODE(NODE_ID, NODE_VALUE) AS NODE
FROM TREE_COLL
PIVOT (CAST(COLLECT(NODE) AS TREE_NODES) FOR NODE_LEVEL IN (1 AS REGION_NODES,
2 AS DEPARTMENT_NODES,
3 AS AREA_NODES,
4 AS CENTRE_NODES
);yet, both fail with
ORA-56902: expect aggregate function inside pivot operationInvestigating further, I found the same behaviour when using XMLAGG as the aggregate function in the PIVOT clause.
Is this normal ? And if it is, is there any other way to achieve the result I was anticipating ?
My version is
SQL> SELECT BANNER FROM V$VERSION;
BANNER
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
PL/SQL Release 11.2.0.3.0 - Production
CORE 11.2.0.3.0 Production
TNS for 64-bit Windows: Version 11.2.0.3.0 - Production
NLSRTL Version 11.2.0.3.0 - ProductionThanks in advance
Best Regards
PhilipMost likely a bug. But you can bypass it by using any other aggregate making sure group consists of a single row and apply collect to a pivoted value. Yes, the cost is double aggregation. And also there is another cost - you would need to create MAP member function otherwise aggreations like MAX/MIN, etc. will not work:
CREATE OR REPLACE TYPE TREE_NODE AS OBJECT
NODE_KEY VARCHAR2( 15 CHAR),
NODE_NAME VARCHAR2(127 CHAR),
map member function f return varchar2
Type created.
CREATE OR REPLACE TYPE BODY TREE_NODE AS
map member function f return varchar2 is
begin
return NODE_NAME;
end f;
end;
Type body created.
CREATE OR REPLACE TYPE TREE_NODES AS TABLE OF TREE_NODE NOT NULL
Type created.
SQL> select *
2 from test_coll
3 /
NODE_ID NODE_VALUE NODE_LEVEL
1 A 1
2 B 2
3 C 3
4 D 4
5 E 1
6 F 2
7 G 3
8 H 4
8 rows selected.
SQL> Now:
SELECT CAST(COLLECT(REGION_NODES) AS TREE_NODES) AS REGIONS,
CAST(COLLECT(DEPARTMENT_NODES) AS TREE_NODES) AS DEPARTMENTS,
CAST(COLLECT(AREA_NODES) AS TREE_NODES) AS AREAS,
CAST(COLLECT(CENTRE_NODES) AS TREE_NODES) AS CENTRES
FROM (
SELECT ROWID RID,
NODE_LEVEL,
TREE_NODE(NODE_ID, NODE_VALUE) AS NODE
FROM TEST_COLL
PIVOT (MAX(NODE) FOR NODE_LEVEL IN (
1 AS REGION_NODES,
2 AS DEPARTMENT_NODES,
3 AS AREA_NODES,
4 AS CENTRE_NODES
REGIONS(NODE_KEY, NODE_NAME) DEPARTMENTS(NODE_KEY, NODE_NAME) AREAS(NODE_KEY, NODE_NAME) CENTRES(NODE_KEY, NODE_NAME)
TREE_NODES(TREE_NODE('1', 'A'), TREE_NODE('5', 'E')) TREE_NODES(TREE_NODE('6', 'F'), TREE_NODE('2', 'B')) TREE_NODES(TREE_NODE('7', 'G'), TREE_NODE('3', 'C')) TREE_NODES(TREE_NODE('8', 'H'), TREE_NODE('4', 'D'))
SQL> SY. -
Aggregate functions cannot be used in group expressions
Hi have report showing sales by Vendor. I need to list all the vendors with Monthly Total>5000 and combine the rest as "OTHER VENDORS"
Vendor is a Group in my report, so I tried to put an expression as a Group on:
=IIF(Sum(Fields!Mth_1_Sales.Value)>5000,Fields!Vendor_No.Value,"OTHER VENDORS")
I've got an error: "aggregate functions cannot be used in group expressions"
How do I get Vendors with Sales < 5000 into "OTHER VENDORS" ?Hi,
You need to group by Month on group expression,
And you can use the same expression in the report column as
=IIF(Sum(Fields!Mth_1_Sales.Value)>5000,Fields!Vendor_No.Value,"OTHER VENDORS")
Many Thanks
..................................................................................................................................................................Please
mark the post as Please mark the post as answered if this post helps to solve the post. -
How can I use User-Defined Aggregate Functions in Timesten 11? such as ODCI
Hi
we are using Timesten 11 version and as per the documentation, it doesn't support User-Defined Aggregate Functions.
So we are looking for alternatives to do it. Could you please provide your expert voice on this.
Thanks a lot.
As the following:
create or replace type strcat_type as object (
cat_string varchar2(32767),
static function ODCIAggregateInitialize(cs_ctx In Out strcat_type) return number,
member function ODCIAggregateIterate(self In Out strcat_type,value in varchar2) return number,
member function ODCIAggregateMerge(self In Out strcat_type,ctx2 In Out strcat_type) return number,
member function ODCIAggregateTerminate(self In Out strcat_type,returnValue Out varchar2,flags in number) return
number
How can I use User-Defined Aggregate Functions in Timesten 11? such as ODCIAggregateInitialize ?Dear user6258915,
You absolutely right, TimesTen doesnt support object types (http://docs.oracle.com/cd/E13085_01/doc/timesten.1121/e13076/plsqldiffs.htm) and User-Defined Aggregate Functions.
Is it crucial for your application? Could you rewrite this functionality by using standart SQL or PL/SQL?
Best regards,
Gennady -
Can't have aggregate function in WHERE clause clause
Dear all,
I've created object in BO XI 3.1 Designer with following criterias:
http://img4.imageshack.us/img4/833/20111201124314.th.jpg
It is a simple number - 1,2,3,4,5.
Now I need to use this object as a criteria for WHERE function in another object.
http://img607.imageshack.us/img607/1543/20111201124717.th.jpg
I receive an error "Can't have aggregate function in WHERE clause <clause>"
How can I overcome this?
P.S. I'm sorry in advance if such topic already exist - I didn't found one.
Edited by: Ashot Antonyan on Dec 1, 2011 9:50 AM
Edited by: Ashot Antonyan on Dec 1, 2011 9:51 AMHi,
You will have to use Sub query to achieve this. Give more details on what is available and what you need then i could help you out with the complete solution.
Thanks,
Ravichandra K -
Any difference between distinct and aggregate function in sql query cost???
Hi,
I have executed many sql stmts patterns- such as:
a) using a single table
b) using two tables, using simple joins or outer joins
but i have not noticed any difference in sql stmts in cost and in execution plan....
Anyway, my colleague insists on that using aggregate function is less costly compared to
distinct....(something i have not confirmed, that's why i beleive that they are exactly the same...)
For the above reffered 1st sql pattern.. we could for example use
select distinct deptno
from emp
select count(*), deptno
from emp
group by deptno select distinct owner, object_type from all_objects
select count(*), owner, object_type from all_objects
group by owner, object_typeHave you found any difference between the two ever...????
Note: I use Ora DB 10g v2.
Thank you,
Simdistinct and aggregate function are for different uses and may give same result but if u r using aggregate function to get distinct records, it will be expensive...
ex
select distinct deptno from scott.dept;
Statistics
0 recursive calls
0 db block gets
2 consistent gets
0 physical reads
0 redo size
584 bytes sent via SQL*Net to client
488 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
4 rows processed
select deptno from scott.emp group by deptno;
Statistics
307 recursive calls
0 db block gets
60 consistent gets
6 physical reads
0 redo size
576 bytes sent via SQL*Net to client
488 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
6 sorts (memory)
0 sorts (disk)
3 rows processed
Nimish Garg
Software Developer
*(Oracle & ASP.NET)*
Indiamart Intermesh Limited, Noida
To Get Free Oracle & ASP.NET Code Snippets
Follow: http://nimishgarg.blogspot.com -
Using Aggregate function in queries
Hi all,
Please take a look on this query and suggest me why i'm getting the error..
This is my simple query using aggregate function in it..
SELECT T1.NAME, T1.DESCRIPTION, SUM(T2.QUANTITY)
FROM TABLE1 T1, TABLE2 T2
WHERE T1.ID=T2.ID
GROUP BY T1.NAME, T1.DESCRIPTION
Above query added with a sub-query in the select segment..
SELECT T1.NAME, T1.DESCRIPTION, SUM(T2.QUANTITY), (SELECT AVG(T3.PRICE) FROM TABLE1 TT1, TABLE3 T3 WHERE TT1.ID=T3.ID AND TT1.ID=T1.ID) AV_PRICE
FROM TABLE1 T1, TABLE2 T2
WHERE T1.ID=T2.ID
GROUP BY T1.NAME, T1.DESCRIPTION
When i add a sub-query which has aggregate function in it, i'm getting the 'ORA-00979: not a GROUP BY expression' error.What is your DB Version. Your query works without any issue in my DB. I used WITH clause to create the sample data. The query highlighted in BLUE is the actual query.
SQL> select * from v$version where rownum = 1;
BANNER
Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bi
SQL> with table1
2 as
3 (
4 select 1 id, 'karthick' name, 'user name' description from dual
5 ),
6 table2
7 as
8 (
9 select 1 id, 100 quantity from dual
10 ),
11 table3
12 as
13 (
14 select 1 id, 10 price from dual
15 )
16 select t1.name
17 , t1.description
18 , sum(t2.quantity)
19 , (
20 select avg(t3.price)
21 from table1 tt1
22 , table3 t3
23 where tt1.id = t3.id
24 and tt1.id = t1.id
25 ) av_price
26 from table1 t1
27 , table2 t2
28 where t1.id = t2.id
29 group
30 by t1.name
31 , t1.description;
NAME DESCRIPTI SUM(T2.QUANTITY) AV_PRICE
karthick user name 100 10
SQL> -
Aggregate Function in SQL subquery
Hello,
I am trying to use the following syntax and it is saying I can't use an aggregate function in a subquery. I can't use a GROUP BY in this case because if another field in the project table (such as status) is different, that project will show up twice.
So in this case I am using this syntax to show the most recent quote within the project.
SELECT PROJECT.*, QUOTE.QuoteDate, QUOTE.QuoteCode
FROM PROJECT LEFT JOIN QUOTE ON PROJECT.ProjectID = QUOTE.ProjectID
WHERE QUOTE.QuoteDate=(SELECT Max(Q.QuoteDate) FROM QUOTE Q WHERE Q.ProjectID = PROJECT.ProjectID);
My goal here is to show the most recent quote within each project (there can be multiple revisions of a quote within each project). I want to show other fields such as the status of the quote, but if the status is different between quotes, the GROUP BY on that
field will cause it to be listed more than once. All I want to show is the most recent quote for each project.
Let me know if this isn't clear.
Thanks.Try the below querySELECT P1.projectID,p1.QuoteDate, Q1.QuoteCode,p1.*
FROM PROJECT P1 inner join (SELECT Q.ProjectID,Max(Q.QuoteDate) QD FROM QUOTE Q group by Q.ProjectID) Q1 on Q1.ProjectID = P1.ProjectID and Q1.QD=P1.QuoteDate-Prashanth -
How to use Aggregate Functions during Top N analysis?
Say i want to find top 5 highest salaries and their totals and average. In that case how to use aggregate functions. Please give me an example on this.
Regards,
Renu
Message was edited by:
user642387Hi,
Yes, you can do that with aggregate functions.
First, do a sub-query to retrieve all the salaries (in descending order), then say "WHERE ROWNUM <= 5" in the main query. Use the aggregate SUM and AVG functions in the main query.
Analytic functions are easier to use for jobs like this, once you get familiar with them. If you're not leaving the field this month, then it's probably worthwhile for you to get familiar with analytic functions. -
Facing problem while using aggregate functions.
I am trying to use aggregate functions such as sum, count in my CQL query.
It is not giving me an error but i am unable to get the correct output out of that.
Query is:
<?xml version="1.0" encoding="UTF-8"?>
<wlevs:config xmlns:wlevs="http://www.bea.com/ns/wlevs/config/application"
xmlns:jdbc="http://www.oracle.com/ns/ocep/config/jdbc">
<processor>
<name>APL_EFW_CostEvent_Processor</name>
<rules>
<view id="CostEventView"
schema="eventName eventType eventId opportunityStatusId opportunity_cost APL_Event_Inbound"><![CDATA[
SELECT X.eventName, X.eventType,
X.eventId, X.opportunityStatusId,
X.opportunity_cost,X.APL_Event_Inbound
from APL_EFW_Master_Inbound_Channel
XMLTable (
'/' PASSING BY VALUE APL_EFW_Master_Inbound_Channel.APL_Event_Inbound as "."
COLUMNS
eventId char(256) PATH 'fn:data(Event/EventHeader/eventId)',
eventName char(256) PATH 'fn:data(Event/EventHeader/eventName)',
eventType char(256) PATH 'fn:data(Event/EventHeader/eventType)',
opportunityStatusId char(256) PATH 'fn:data(Event/ApplicationDataArea/opportunity/opportunity_details/opportunity_status)',
opportunity_cost char(256) PATH 'fn:data(Event/ApplicationDataArea/opportunity/opportunity_details/opportunity_cost)',
APL_Event_Inbound xmltype path '/'
) AS X
]>
</view>
<query id="CostEventQuery">
<![CDATA[
SELECT
XMLELEMENT("opportunity",
XMLELEMENT("cost_opportunity",
XMLFOREST(X.opportunity_cost))) as APL_Event_Inbound
FROM CostEventView
MATCH_RECOGNIZE (
MEASURES
A.opportunity_cost as opportunity_cost
PATTERN (B A+) within 30000 milliseconds
DEFINE
A as sum(A.opportunity_cost)> 1000 )
as X
]]>
</query>
</rules>
</processor>
</wlevs:config>
The problem i am getting is when the value is getting compared with the opportunity cost rather than with the sum of oppCost
A as sum(A.opportunityCost)>1000
A as A.opportunityCost >1000
Both the cases are treated as same .It would help if you could provide sample input data and associated output that illustrates the problem
-
Problem while using aggregate functions in EJB QL 2.1
Hai all,
I am using aggregate function as follows
select max(c.id) from customer as c
for this iam selected check box EJB QL 2.1 in persistent.xml
this is validated by nwds, but while deploying server raising error like ejb ql syntax error.
Actually according to EJB QL 2.1 this is a valid query, what i need to do for run this same query .
Anybody please help me in this regard
Regards
SomarajuBeevin
Both two are not even validated,
but with the first one as select max(c.id) from customer as c , in this case it is validated but while deploying it is error as , object must be return
But when i saw the ejb2.1 specification we can write this type of queries also ?
Is it problem with was any thing
Regards
Somaraju
Maybe you are looking for
-
File Open ... then all greyed out?
Greetings, CS5, 12.0.1, iMac, with 2.8 GHz INtel Core i7. If I ask CS5 to open a file (File>Open) all menus simply grey out, and no dialog box appears to allow navigation to the file to be opened. Ultimately I have to Force Quit, though Photoshop is
-
Error while Starting Sun One Portal Server 6.0
Hi Everyone, I am trying to install Sun One Portal Server 6.0 Installation. When I start the server (./amserver startall) , I am getting the following in the console ========================= starting auth helpers ... done. checking for directory ser
-
Iahve an 09 macbook and I am trying to download the 11.1 version of itunes, but it wont open and my computer is saying that I have the latest version, 10.6. What can i do? I need this for my phone
-
Unable to insert into table of PointBase database
Hi, I have written one sample application which uses PointBase of JSC. It was working fine but now while trying to insert a record into table I am getting this exception javax.faces.el.EvaluationException: javax.faces.FacesException: java.sql.SQLExce
-
Hello everyone, right now i have an ABAP-function-module which i have to convert into Java-Code. My problem is: i don't really understand ABAP so i have some questions. The part which i don't understand is this: READ TABLE t_ctab INDEX f_char. IF