Aggregate function and join
I have three Tables(Emptimesheet,comexpensetable,perexpensestable).I want to show otput something like below,
EmpID,EmpName,StartDate,EndDate,Total,Chotel,CAirfare,Cfuel,WeeklCompanyExpenses,Percompanyexpenses
rightnow in the below query I don't have hotel,airfare,fuel.
select distinct(e.EmpID) ,e.EmpName, e.StartDate,e.EndDate,e.Total,c.WeeklyComtotalExpenses,p.WeeklyPerTotalExpenses
from EmpTimeSheet e left JOIN ComExpensesTable c on c.CExpID=e.EmpID left join PerExpensesTable p ON p.PExpID=e.EmpID
Output for Above query .
EmpID name sd ED Total companEx PerExpense 1 tom 2014-02-02 00:00:00.000 2014-02-08 00:00:00.000 28:30:0 213.00 199.00
3 nick 2014-03-02 00:00:00.000 2014-03-08 00:00:00.000 15:20:0 16.00 NULL
4 john 2014-03-23 00:00:00.000 2014-03-29 00:00:00.000 42:0:0 NULL NULL
5 test 2014-03-09 00:00:00.000 2014-03-15 00:00:00.000 34:15:0 NULL NULL
6 ema 2014-04-13 00:00:00.000 2014-04-19 00:00:00.000 39:0:0 16.00 NULL
Output Emptimesheet
id empname startdate enddate .. total 1 tom 2014-02-02 00:00:00.000 2014-02-08 00:00:00.000 Thurs 2014-02-06 00:00:00.000 Travel Time 28:30:0
3 nick 2014-03-02 00:00:00.000 2014-03-08 00:00:00.000 Mon 2014-03-03 00:00:00.000 Onsite/WalkTesting 40:0:0
4 john 2014-03-23 00:00:00.000 2014-03-29 00:00:00.000 Mon 2014-03-24 00:00:00.000 Onsite/WalkTesting 42:0:0
5 test 2014-03-09 00:00:00.000 2014-03-15 00:00:00.000 Mon 2014-03-10 00:00:00.000 Travel Time , 34:15:0
6 ema 2014-04-13 00:00:00.000 2014-04-19 00:00:00.000 Mon 2014-04-14 00:00:00.000 Equipment Testing 39:0:0
output for ComExpenseTable
CExpID airfare hotel weeklycomexpensetable 1 45.00 34.00 213.00
3 5.00 3.00 16.00
6 5.00 3.00 16.00
output for Perexpensetable
PExpID PerExpenseTable1 Sun 2014-02-02 00:00:00.000 199.00
2 Sun 2014-02-23 00:00:00.000 199.00
below query for sum of indivial expense in company table
select sum(CHotel) as Hotel ,sum(CTransport) as Airfare,sum(CMeals) as Meals,sum(CFuel) as Gas,sum(CTolls),Sum(CParking) as Parking,Sum(CMisc) as Misc ,sum(CMileage) as Mileage from ComExpensesTable where CExpID=1
Now I want to add sum of hotel,transport .. to the below query .I don't know how to do this.Any suggestions please?
select distinct(e.EmpID) ,e.EmpName, e.StartDate,e.EndDate,e.Total,c.WeeklyComtotalExpenses,p.WeeklyPerTotalExpenses
from EmpTimeSheet e left JOIN ComExpensesTable c on c.CExpID=e.EmpID left join PerExpensesTable p ON p.PExpID=e.EmpID
select
distinct(e.EmpID) ,
e.EmpName,
e.StartDate,
e.EndDate,
e.Total,
ee.Hotel,
ee.Airfare,
c.WeeklyComtotalExpenses,
p.WeeklyPerTotalExpenses
fromEmpTimeSheet e
left JOIN (select CExpID, sum(CHotel) as Hotel ,sum(CTransport) as Airfare,
sum(CMeals) as Meals,sum(CFuel) as Gas,sum(CTolls),
Sum(CParking) as Parking,Sum(CMisc) as Misc ,
sum(CMileage) as Mileage from ComExpensesTable group by CExpID) cleft join // don't need the "left join" hereon c.CExpID=e.EmpID //error
left join PerExpensesTable p ON p.PExpID=e.EmpID
Similar Messages
-
Aggregate functions and normal function in SELECT statement
hi
i am using MS Access DataBase ...
i have lot of integer coloumns in my Database
i want to retrieve the coloumn values as well as the min , max and avg of that coloumn
i dont know whether its possible to do in a single statement or not
generally if we retrieve the values of a particular coloum
we say " SELECT length FROM TABLENAME WHERE somecondition"
and then get the values as int len = rs.getInt("length")..... over a loop
but how to retieve the value of an aggregate function?
like if i say "SELECT avg(colname),max(colname),min(colname) FROM TABLENAME WHERE somecondition"
how do i retrieve this value ???
i dont know if its possible or not ....pls help.........Give names too each column
SELECT avg(colname) average,max(colname) max,....
and then rs.getInt("average")
This works in Oracle and Sybase, not sure on MS access tough -
Database Aggregate Functions and Oracle Discoverer
Hello Guys.
There are a lot of aggregate function inside the database, unfortunatelly some of them are not directly accesible from Oracle Discoverer.
For example :
STATS_BINOMIAL_TEST
STATS_CROSSTAB
STATS_F_TEST
STATS_KS_TEST
STATS_MODE
STATS_MW_TEST
STATS_ONE_WAY_ANOVA
STATS_T_TEST_*
STATS_WSR_TEST
What is the best way to incorporate this kind of function in Oracle Discoverer ?
Thanks
Ramiro Ortiz RiosWhile Discoverer today is unable to recognize these Oracle Database functions, we are looking at adding this capability into the product. If you think this is important, please take the poll at http://oraclebi.blogspot.com/2006/04/must-have-in-discoverer.html
Also, if you can spare a few minutes, do send me a mail at abhinav.oracle at gmail.com with a brief description of a use case that describes where and how these functions would be used.
Thanks
Abhinav
Oracle Business Intelligence Product Management
BI on Oracle: http://www.oracle.com/bi/
BI on OTN: http://www.oracle.com/technology/products/bi/
Documentation: http://docs.oracle.com/
Oracle BI Suite EE: http://www.oracle.com/technology/products/bi/enterprise-edition.html
Oracle BI Suite SE: http://www.oracle.com/technology/products/bi/standard-edition.html
Oracle BI Suite SE One: http://www.oracle.com/technology/products/bi/standard-edition-one.html
Discoverer: http://www.oracle.com/technology/products/discoverer/
BI Software: http://www.oracle.com/technology/software/products/ias/devuse.html
BI Blog: http://oraclebi.blogspot.com/
Blogs: http://blogs.oracle.com/ -
Selecting both a aggregate function and another field
I am trying to do something very simple but I am not sure of the syntax.
I would like to select all of the petid's and find the count of the pets in a given city, both from the same table, Pets.
Can somebody please help me with this?
ThanksHi,
An aggregate function will give you one row of output per group.
For example, if you use the aggregate COUNT function to get the total number of rows in a whole table, then you can only have one row of output, representing the whole table, so, if I understand the problem, you can't (easily) use an aggregate function.
Almost all of the aggregate functions have analytic counterparts, that can produce the same results without collapsing the result set into one row per group.
I think this is what you requested:
SELECT petid
, COUNT (*) OVER (PARTITION BY 1) AS total_cnt
FROM pets
WHERE city = 'Paris' -- or whatever
;Sorry, I'm not at a database now, so I can't check, but I think you don't need the PARTITION BY clause, so you can also say:
, COUNT (*) OVER () AS total_cntThe keyword OVER marks this as an analytic, rather than an aggregate, function. -
SQL Aggregate function and Subquery issues
Hello,
I'm trying to create an SQL statement that gives the rate of all Urgent surgeries Grouped by sector (i.e Surgery, Radiology), and Fiscal year
To do this I need to divide the sum of surgeries with a state "Urgent" by the total surgeries
In order to pull all the Total surgeries I would need to exclude the surgeries with the state "Cancelled", AND make sure to get rid of duplicates a single surgery may have.
So this is what I came up with, but I'm not able to apply the following formula in SQL for the rate of Urgent surgeries:
TOTAL OF URGENT SURGERIES / TOTAL SURGERIES
Note that the Select statement within the WITH CLAUSE runs successfully when running it separately
With T1 As(
SELECT
b."etat",
c."secteur",
d.annee_fiscale_full,
d.periode,
SUM(Count(distinct b."Cle_requete")) OVER (PARTITION BY b."etat", c."secteur", d.annee_fiscale_full, d.periode) AS TOTAL_SURGERIES
FROM vsRequete a,
vsEtats b,
vsOperation c,
periode_financiere d,
vstemps_operatoires e
WHERE b."etat" <> 'Cancelled'
AND (b."Cle_requete" = a."Cle_vsRequete")
AND (c."Cle_requete" = a."Cle_vsRequete")
AND (b."Cle_requete" = c."Cle_requete")
AND (a."Cle_vsRequete" = e."Cle_requete")
AND c."date_operation" = d.per_fina_date
GROUP BY
b."etat",
c."secteur",
--a."type_visite",
d.annee_fiscale_full,
d.periode )
SELECT
---- ***NOTE***: SHOULD I BE USING THE FOLLOWING ANALYTIC FUNCTION FOR THE RATE OF URGENT SURGERIES
---- RATIO_TO_REPORT(T1.TOTAL_SURGERIES) OVER () As URGENT_SURGERY_RATE,
T1."secteur",
--a."type_visite",
T1.annee_fiscale_full,
T1.periode
FROM T1
Where T1."etat" = 'Urgent'
ORDER BY
T1.annee_fiscale_full,
T1.periode,
T1."secteur";
Thanks for your help
Edited by: Ruben_920841 on Dec 21, 2012 1:40 PM
Edited by: Ruben_920841 on Dec 21, 2012 1:41 PMHi,
Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved.
Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
Always say which version of Oracle you're using (for example, 11.2.0.2.0).
See the forum FAQ {message:id=9360002}
Ruben_920841 wrote:
Hello,
I'm trying to create an SQL statement that gives the rate of all Urgent surgeries Grouped by sector (i.e Surgery, Radiology), and Fiscal year
To do this I need to divide the sum of surgeries with a state "Urgent" by the total surgeries
In order to pull all the Total surgeries I would need to exclude the surgeries with the state "Cancelled", AND make sure to get rid of duplicates a single surgery may have.
So this is what I came up with, but I'm not able to apply the following formula in SQL for the rate of Urgent surgeries:
TOTAL OF URGENT SURGERIES / TOTAL SURGERIES
Note that the Select statement within the WITH CLAUSE runs successfully when running it separately
With T1 As(
SELECT
b."etat",
c."secteur",
d.annee_fiscale_full,
d.periode,
SUM(Count(distinct b."Cle_requete")) OVER (PARTITION BY b."etat", c."secteur", d.annee_fiscale_full, d.periode) AS TOTAL_SURGERIES Is it possible, in a group of rows with the same "Cle_requete", for some rows to have "etate"='Urgent' and other rows to have some other value besides 'Cancelled'? If so, how is that counted? Include an example or two in your sample data and results.
FROM vsRequete a,
vsEtats b,
vsOperation c,
periode_financiere d,
vstemps_operatoires e
WHERE b."etat" <> 'Cancelled'This site doesn't like to display the <> inequality operator. Always use the other (equivalent) inequality operator, !=, when posting here.
AND (b."Cle_requete" = a."Cle_vsRequete")
AND (c."Cle_requete" = a."Cle_vsRequete")
AND (b."Cle_requete" = c."Cle_requete")
AND (a."Cle_vsRequete" = e."Cle_requete")
AND c."date_operation" = d.per_fina_date
GROUP BY
b."etat",
c."secteur",
--a."type_visite",
d.annee_fiscale_full,
d.periode )
Select
----- ***NOTE***: SHOULD I BE USING THE FOLLOWING ANALYTIC FUNCTION FOR THE RATE OF URGENT SURGERIES
------ RATIO_TO_REPORT(T1.TOTAL_SURGERIES) OVER () As URGENT_SURGERY_RATE,That depends on your data, and your desired results. Based on what you've said so far, I think not. It's more likely that you'll want to use a CASE expression to get a count of the 'Urgent' surgeries.
T1."secteur",
--a."type_visite",
T1.annee_fiscale_full,
T1.periode
FROM T1
Where T1."etat" = 'Urgent'
ORDER BY
T1.annee_fiscale_full,
T1.periode,
T1."secteur";The forum FAQ {message:id=9360002} explains how to use \ tags to preserve spacing when you post formatted text, such as your query.
It sounds like your problem is similar to this one:
"What percentage of the employees (not counting SALESMEN) in each department of the scott.emp table are CLERKS?"
Here's one way you might answer that:WITH got_cnts AS
SELECT deptno
, COUNT ( DISTINCT CASE
WHEN job = 'CLERK'
THEN ename
END
) AS clerk_cnt
, COUNT (DISTINCT ename) AS total_cnt
FROM scott.emp
WHERE job != 'SALESMAN'
GROUP BY deptno
SELECT deptno
, clerk_cnt
, total_cnt
, 100 * clerk_cnt
/ total_cnt AS clerk_pct
FROM got_cnts
ORDER BY deptno
Output:DEPTNO CLERK_CNT TOTAL_CNT CLERK_PCT
10 1 3 33.33
20 2 5 40.00
30 1 2 50.00 -
Aggregate Functions and Difference
I had posted this question earlierRCOUNT and RSUM but if that was too many details, let me simplify it here.
Month_Number -----Count(Orders)----------Increase In Sales
1-------------------------100------------------------- -
2-------------------------400------------------------- 300
3-------------------------280------------------------- -20
This is what Im looking for. As I have to use the Count() I am using Group By on Month_Number.
RSUM didn't work in this case. Any solution to get this working ?
Thanks
Edited by: user558238 on Jan 19, 2009 11:06 PMAs you have only one period in the difference.
For instance :
Month 2 - Month 1
and not
Month 3 - Month 1
You can use this formula :
MSUM (CountOrders, 2) - 2 * CountOrdersIt calculate a moving sum on 2 periods and subtract 2 sum of the current period.
Otherwise, you can use the Time function series (AGO, TODATE) but it's only possible in the repository layer and not in the Business presentation layer :
http://gerardnico.com/wiki/dat/obiee/bi_server/design/dimension/time_dimension_parameters_for_ago_and_td_functions
AGO(CountOrders, SH.TimesDim."Month", 1)An other solution will be the use of a sql function.
Success
Nico -
Where clause in COUNT function and joining two queries
I have a table that I am trying to count the number of course passed, and also list the modules passed as well.
the first problem I am having is what to put in the where variable , so that its not specific to a customer(I can use the query below for a particular customer and a particular course)but I will like a generic query where the result will be distinct in terms
of user and course like the one below
select FirstName,LastName,CourseTitle,Noofmodules, count (Coursecompleted) as modulescompleted from EStudentsprogress where Coursecompleted = '1'and EmailAddress = '[email protected]'
and CourseTitle = 'Microsoft MOS 2010 EXCEL' Group by FirstName, LastName, CourseTitle, Noofmodules ;
How can i make it list the result as above, whereby i dont specify the email address or course title(trying to get the result for all the clients )
. Also I have a query that list the courses that is passed by the customer, I will like the column with the list of courses passed be added to the result above, but as a column for each course.
select FirstName,LastName,CourseTitle, EmailAddress, CourseModule as coursepassed from EStudentsprogress where coursecompleted =1
cheersDo you mean this?
select FirstName,
LastName,
CourseTitle,
Noofmodules,
count (Coursecompleted) as modulescompleted,
STUFF((SELECT ',' + CourseTitle
FROM EStudentsprogress
WHERE FirstName = e.FirstName
AND LastName = e.LastName
WHERE Coursecompleted = '1'
FOR XML PATH('')),1,1,'') AS CoursesCompleted
from EStudentsprogress e
where Coursecompleted = '1'
Group by FirstName, LastName, CourseTitle, Noofmodules ;
If not please provide some sample data and explain the output you want
Please Mark This As Answer if it solved your issue
Please Mark This As Helpful if it helps to solve your issue
Visakh
My MSDN Page
My Personal Blog
My Facebook Page
I AM HAVING Incorrect syntax near the keyword 'WHERE'.
It was a typo
try this
select FirstName,
LastName,
CourseTitle,
Noofmodules,
count (Coursecompleted) as modulescompleted,
STUFF((SELECT ',' + CourseTitle
FROM EStudentsprogress
WHERE FirstName = e.FirstName
AND LastName = e.LastName
AND Coursecompleted = '1'
FOR XML PATH('')),1,1,'') AS CoursesCompleted
from EStudentsprogress e
where Coursecompleted = '1'
Group by FirstName, LastName, CourseTitle, Noofmodules ;
Please Mark This As Answer if it solved your issue
Please Mark This As Helpful if it helps to solve your issue
Visakh
My MSDN Page
My Personal Blog
My Facebook Page
its populating all the result for a particular customer, so i added another clause to it and it worked
select FirstName,
LastName,
CourseTitle,
Noofmodules,
count (Coursecompleted) as modulescompleted,
STUFF((SELECT ',' + CourseTitle
FROM EStudentsprogress
WHERE FirstName = e.FirstName
AND LastName = e.LastName
AND Coursecompleted = '1'
AND CourseTitle = e.CourseTitle
FOR XML PATH('')),1,1,'') AS CoursesCompleted
from EStudentsprogress e
where Coursecompleted = '1'
Group by FirstName, LastName, CourseTitle, Noofmodules ;
but the result of the column is long , so i tried to used the course module, which is a column with numbers, and i tried modifying the query , but i had Error converting data type varchar to float.( i checked and saw that stuff is for concatinating
strings) is there a way around it.
i used
select FirstName,
LastName,
CourseModule,
CourseTitle,
Noofmodules,
count (Coursecompleted) as modulescompleted,
STUFF((SELECT ',' + CourseModule
FROM EStudentsprogress
WHERE FirstName = e.FirstName
AND LastName = e.LastName
AND Coursecompleted = '1'
AND CourseTitle = e.CourseTitle
FOR XML PATH('')),1,1,'') AS CoursesCompleted
from EStudentsprogress e
where Coursecompleted = '1'
Group by FirstName, LastName,CourseModule, CourseTitle, Noofmodules ; -
Custom aggregate function inside a package.
Hi there,
I'm trying to write a custom aggregate function and group that function inside a package together with some other functions that I have. As an example (to simulate the problem I have) suppose my custom aggregation to do a summation of numbers looks like:
CREATE OR REPLACE TYPE SUM_AGGREGATOR_TYPE AS OBJECT (
summation NUMBER,
STATIC FUNCTION ODCIAggregateInitialize(agg_context IN OUT
SUM_AGGREGATOR_TYPE) RETURN NUMBER,
MEMBER FUNCTION ODCIAggregateIterate(self IN OUT SUM_AGGREGATOR_TYPE,
next_number IN NUMBER) RETURN NUMBER,
MEMBER FUNCTION ODCIAggregateMerge(self IN OUT SUM_AGGREGATOR_TYPE,
para_context IN SUM_AGGREGATOR_TYPE) RETURN NUMBER,
MEMBER FUNCTION ODCIAggregateTerminate(self IN SUM_AGGREGATOR_TYPE,
return_value OUT NUMBER, flags IN NUMBER) RETURN NUMBER
CREATE OR REPLACE TYPE BODY SUM_AGGREGATOR_TYPE IS
STATIC FUNCTION ODCIAggregateInitialize(agg_context IN OUT
SUM_AGGREGATOR_TYPE)
RETURN NUMBER IS
BEGIN
agg_context := SUM_AGGREGATOR_TYPE(NULL);
RETURN ODCIConst.Success;
END;
MEMBER FUNCTION ODCIAggregateIterate(self IN OUT SUM_AGGREGATOR_TYPE,
next_number IN NUMBER)
RETURN NUMBER IS
BEGIN
IF self.summation IS NULL THEN
self.summation := next_number;
ELSIF summation IS NOT NULL THEN
self.summation := self.summation + next_number;
END IF;
RETURN ODCIConst.Success;
END;
MEMBER FUNCTION ODCIAggregateMerge(self IN OUT SUM_AGGREGATOR_TYPE,
para_context IN SUM_AGGREGATOR_TYPE)
RETURN NUMBER IS
BEGIN
self.summation := self.summation + para_context.summation;
RETURN ODCIConst.Success;
END;
MEMBER FUNCTION ODCIAggregateTerminate(self IN SUM_AGGREGATOR_TYPE,
return_value OUT NUMBER, flags IN NUMBER)
RETURN NUMBER IS
BEGIN
return_value := self.summation;
return ODCIConst.Success;
END;
END;
If I write the following function definition:
CREATE OR REPLACE FUNCTION MY_SUM(input NUMBER)
RETURN NUMBER PARALLEL_ENABLE AGGREGATE USING SUM_AGGREGATOR_TYPE;
and corresponding type declaration to test:
CREATE OR REPLACE TYPE VECTOR
IS
TABLE OF NUMBER;
this statement:
select my_sum(column_value) from table(vector(1, 2, 1, 45, 22, -1));
gives the correct result of 70. However, creating a package with the function definition:
CREATE OR REPLACE PACKAGE MY_FUNCTIONS AS
FUNCTION MY_SUM(input NUMBER)
RETURN NUMBER PARALLEL_ENABLE AGGREGATE USING SUM_AGGREGATOR_TYPE;
END;
and calling it via:
select MY_FUNCTIONS.my_sum(column_value) from table(vector(1, 2, 1, 45, 22, -1));
explodes with:
ORA-00600: internal error code, arguments: [17090], [], [], [], [], [], [], [], [], [], [], []
Is it possible to have custom aggregate functions nested inside package declarations?
I'm using Oracle 11g, Release 2 (11.2.0.1.0).HiddenName wrote:
Is it possible to have custom aggregate functions nested inside package declarations?Yes, it is possible, you have succesfuly created your function. Your problem is that the database throws ORA-600 on execute. And with ORA-600 you can do 2 things: 1) google ORA-600 17090 or 2) contact your Oracle Support.
You could also try to declare the function without PARALLEL_ENABLE - just to try to see if it changes anything. You can also try to call your function against a regular table with rows and columns - not against an collection type with table() operator.
Anyway - these 2 tests should be usefull for Oracle Support.
I never tried to put a custom aggregate function into a package. First - the cases when you need a custom aggregate function to be written for your system are very rare. Second - even if I needed 1 then I never needed 2 or more custom aggregate functions on my system. And as I do not like to make my life more complex than necessary, I have created it as a stand-alone function. And it is works (slowly).I tried using a standard table as you suggested:
CREATE TABLE TEST_DATA
test_value NUMBER
INSERT INTO TEST_DATA
(SELECT column_value test_value from TABLE(vector(1, 2, 1, 45, 22, -1)));
COMMIT;
select my_sum(test_value) from test_data;
select my_functions.my_sum(test_value) from test_data;
I also tried removing the PARALLEL_ENABLE clause to create the package as follows:
CREATE OR REPLACE PACKAGE MY_FUNCTIONS AS
FUNCTION MY_SUM(input NUMBER)
RETURN NUMBER AGGREGATE USING SUM_AGGREGATOR_TYPE;
END;
And unfortunately it still breaks with the following error: SQL Error: ORA-00600: internal error code, arguments: [17090]. This looks like an Oracle bug to me as the PL/SQL parsing engine should have disallowed me to even create this if it is not supported in Oracle. Instead, it allows me to create the package, and breaks when I call the function with this weird error (additionally cutting my connection from the database) instead of disallowing me to do this altogether and printing a nice error message telling me that Oracle doesn't support this. How would I go about logging a ticket for this?
Edited by: wcmatthysen on Dec 1, 2010 12:51 PM -
Need complex query with joins and AGGREGATE functions.
Hello Everyone ;
Good Morning to all ;
I have 3 tables with 2 lakhs record. I need to check query performance.. How CBO rewrites my query in materialized view ?
I want to make complex join with AGGREGATE FUNCTION.
my table details
SQL> select from tab;*
TNAME TABTYPE CLUSTERID
DEPT TABLE
PAYROLL TABLE
EMP TABLE
SQL> desc emp
Name
EID
ENAME
EDOB
EGENDER
EQUAL
EGRADUATION
EDESIGNATION
ELEVEL
EDOMAIN_ID
EMOB_NO
SQL> desc dept
Name
EID
DNAME
DMANAGER
DCONTACT_NO
DPROJ_NAME
SQL> desc payroll
Name
EID
PF_NO
SAL_ACC_NO
SALARY
BONUS
I want to make complex query with joins and AGGREGATE functions.
Dept names are : IT , ITES , Accounts , Mgmt , Hr
GRADUATIONS are : Engineering , Arts , Accounts , business_applications
I want to select records who are working in IT and ITES and graduation should be "Engineering"
salary > 20000 and < = 22800 and bonus > 1000 and <= 1999 with count for males and females Separately ;
Please help me to make a such complex query with joins ..
Thanks in advance ..
Edited by: 969352 on May 25, 2013 11:34 AM969352 wrote:
why do you avoid providing requested & NEEDED details?I do NOT understand what do you expect ?
My Goal is :
1. When executing my own query i need to check expalin plan.please proceed to do so
http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_9010.htm#SQLRF01601
2. IF i enable query rewrite option .. i want to check explain plan ( how optimizer rewrites my query ) ? please proceed to do so
http://docs.oracle.com/cd/E11882_01/server.112/e16638/ex_plan.htm#PFGRF009
3. My only aim is QUERY PERFORMANCE with QUERY REWRITE clause in materialized view.It is an admirable goal.
Best Wishes on your quest for performance improvements. -
Self Join and Aggregate Functions
Hi all,
I am trying a query in TOAD where I need to use an aggregate function MAX and a self join using a subquery. Its working fine when there is no aggregate function but when I tried to use the MAX function then its running for infi time. Is it because of the invalid joins? or because of the usage of the self join and aggregate func?
The query contains some other tables too....
Any one please help....
Thanks in advance,
GToad will bring back a limited set of rows and present them to you giving the impression that the work is done. Adding an aggregate function requires the entire resultset to be traversed.
Yes, post the 2 queries to verify what I am saying. -
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 pulls an additional table in join
Hello,
We're facing a wierd scenario whereby using an aggregate function in a report brings an additional table in the query, which should not be included. Please throw some light on this if you have any idea why this would happen. Here are the details
OBIEE version: 10.1.3.4
I pull 2 columns in my report - Col1 (numeric column from Dim A), Col2 (date column from Dim B)
I have already set an implicit fact column in that subject area (Col3 from Fact X)
Now when I run this report, the FROM clause of the sql correctly shows Dim A, Dim B, Fact X
Later, I apply a MAX function on Col2 (date column from Dim B). Ideally, the FROM clause of my sql should still be the same. But here is what happens...
FROM Dim A, Dim B, Fact X, Fact Y (Bridge table).
Fact Y is a bridge table that we are using in this subject area. But there is no reason why this table should get pulled in this query just by using an aggregate function in it.
Your thoughts and insights will be highly appreciated.
Thanks,
VahibDid you apply MAX in the aggregate function section? If that is the case, OBIEE is forced to consider logical table for Dim B as a fact and brings in Y as a way to resolve the join between two facts.
Try setting up a new fact and create MAX column there. See if it resolves that problem or not. You may also want to bring Dim B in the LTS of the main fact and create a column with MAX aggregation. That should work too. -
Join tables with aggregate function
Hello
I have 4 views that I need to perform aggregate function, count, on and then join them for query output.
Basically each view has a column with a score and a subcontractor name. One subcontractor may have more than one score in each view.
Here is the sql that I'm working with thus far:
select e.sub_name, (count(e.score) - 1), (count(v.score) - 1), (count(s.score) - 1), (count(u.score) - 1)
from speed.v_ratings_ex e, speed.v_ratings_vg v, speed.v_ratings_sat s, speed.v_ratings_uns u
where v.sub_name = e.sub_name
and s.sub_name = e.sub_name
and u.sub_name = e.sub_name
group by e.sub_name
order by e.sub_name asc;
This results in each column returning the same value b/c the join is performed before the aggregate function.
Can anyone offer some help so that I may get the desired results?You need to use in-line views to perform the aggregates, then join the in-line views.
Something like:
SELECT e.sub_name, e.score - 1 escore, v.score - 1 vscore,
s.score - 1 sscore, u.score - 1 uscore
FROM (SELECT sub_name,count(*) score
FROM v_ratings_ex
GROUP BY sub_name) e,
(SELECT sub_name,count(*) score
FROM v_ratings_vg
GROUP BY sub_name) v,
(SELECT sub_name,count(*) score
FROM v_ratings_sat
GROUP BY sub_name) s,
(SELECT sub_name,count(*) score
FROM v_ratings_uns
GROUP BY sub_name) u
WHERE v.sub_name = e.sub_name and
s.sub_name = e.sub_name and
u.sub_name = e.sub_name
ORDER BY e.sub_name asc;TTFn
John -
Analytic function and aggregate function
What are analytic function and aggregate function. What is difference between them?
hi,
Analytic Functions :----------
Analytic functions compute an aggregate value based on a group of rows. They differ from aggregate functions in that they return multiple rows for each group. The group of rows is called a window and is defined by the analytic_clause. For each row, a sliding window of rows is defined. The window determines the range of rows used to perform the calculations for the current row. Window sizes can be based on either a physical number of rows or a logical interval such as time.
Analytic functions are the last set of operations performed in a query except for the final ORDER BY clause. All joins and all WHERE, GROUP BY, and HAVING clauses are completed before the analytic functions are processed. Therefore, analytic functions can appear only in the select list or ORDER BY clause.
Analytic functions are commonly used to compute cumulative, moving, centered, and reporting aggregates.
Aggregate Functions :----------
Aggregate functions return a single result row based on groups of rows, rather than on single rows. Aggregate functions can appear in select lists and in ORDER BY and HAVING clauses. They are commonly used with the GROUP BY clause in a SELECT statement, where Oracle Database divides the rows of a queried table or view into groups. In a query containing a GROUP BY clause, the elements of the select list can be aggregate functions, GROUP BY expressions, constants, or expressions involving one of these. Oracle applies the aggregate functions to each group of rows and returns a single result row for each group.
If you omit the GROUP BY clause, then Oracle applies aggregate functions in the select list to all the rows in the queried table or view. You use aggregate functions in the HAVING clause to eliminate groups from the output based on the results of the aggregate functions, rather than on the values of the individual rows of the queried table or view.
let me know if you are feeling any problem in understanding.
thanks.
Edited by: varun4dba on Jan 27, 2011 3:32 PM -
How to write SQL query and apply aggregate functions on it
Hello experts,
Iu2019ve a task to write SQL query on tree tables and do inner join on them. Iu2019ve accomplish this task by using T-CODE SQVI. However now I need to write a query and apply SQL functions on it i.e. Add, Count, Max and Min etc. Please can someone tell me how I can write SQL query with aggregate functions in SAP?
Thanks a lot in advanceHI Mr. Cool
you can see the below code for using aggregate functions.
where ARTIST and SEATSOCCU are the field names for which you want to perform these functions.
DATA: TOTAL_ENTRIES TYPE I,
TOTAL_ATT TYPE I,
MAX_ATT TYPE I,
AVG_ATT TYPE I.
SELECT COUNT( DISTINCT ARTIST )
SUM( SEATSOCCU )
MAX( SEATSOCCU )
AVG( SEATSOCCU ) FROM YCONCERT INTO (TOTAL_ENTRIES, TOTAL_ATT,
MAX_ATT, AVG_ATT).
Thanks
Lalit Gupta
Maybe you are looking for
-
How to sum values from multiple lines in a DataTable?
I have a Lookout program which uses a DataTable to allow users to write basic programs (relay on/off times, which relays change state, and pause times). The DataTable cursor position changes to advance from one program stage to another. What I wou
-
Firefox always opens all tabs that were opened when last closed
Firefox, out of the blue, started to always show my tabs from the last session when it is started. I checked that Firefox not listed in the task manager list after closing. So I tried the following: - changing the option "when Firefox starts" to all
-
Hello Experts, I have a question, how I can import "linq" file to ms sql?
Hello Experts, I have a question, how I can import linq (OpenUIPlayersDB.linq) file to ms sql? Form Sample OpenUI applications? BR Lukas
-
V$db_cache_advice issuies.
Hi, i was giving a read to the performance guide doc. where i read that v$db_cache_advise views is populated when we set db_cache_advise parameter to on.it seems ok to me till now,but then next it says 'This view shows the estimated miss rates for tw
-
Network board 10/100 full duplex
I have an issue with my system (solaris 8 sparc): If I download a local file from a distant machine the file is going at about 100Mb. If I try to upload that same file then it is going at 10Mb. I checked the cables etc but could not find anything. nd