Link to home
Start Free TrialLog in
Avatar of KPax
KPax

asked on

Oracle SQL AVG

I have a little confusion with this.
Here is the situation.
There are tables:
PROJEKAT (PROJECT)
with attributes:
SPR (ID FOR PROJECT)
NAP (NAME OF PROJECT)
NAR (ID OF COMPANY WHO ORDERED PROJECT - CUSTOMER)
RUK (ID OF PROJECT MANAGER)

and table:
RADPROJ (EMPLOYEE_PROJECT)
with attributes:
SPR (ID OF PROJECT)
MBR (ID OF EMPLOYEE WORKING ON PROJECT)
BRC (NUMBER OF WORKING HOURS PER PROJECT PER EMPLOYEE)

I was writing a query to get ID of projects at which average working hours are bigger than average working hours on ALL projects.
And here is how it looks like:
--first solution
select rp.spr, p.nap, avg (rp.brc), (select avg (rp.brc) from radproj rp)
from radproj rp, projekat p
where rp.spr = p.spr
group by rp.spr, p.nap
having  avg (rp.brc) > (select avg (rp.brc) from radproj rp );

Open in new window


and it works OK, it yields results:
2      Skladistenje      13      11,15384615384615384615384615384615384615
5      Dijete      15,625      11,15384615384615384615384615384615384615

But to my big surprise this query as well gives same result:
-- second solution
SELECT p.spr, p.nap, AVG(rp.brc), AVG(rp1.brc)
FROM radproj rp, radproj rp1, projekat p
WHERE rp.spr=p.spr
GROUP BY p.spr, p.nap
HAVING AVG(rp.brc)>AVG(rp1.brc);

Open in new window


My question is how come that in second solution
AVG(rp.brc) gives average working hours per employee on project (as it should), but then second AVG(rp1.brc) which is basically exactly the same as first AVG function doesn't give the same but it "figures out" and give exactly what I need and tat is AVG working hours for ALL projects? Why the second AVG(rp1.brc) have not to be in (select avg (rp.brc) from radproj rp) format? What do I miss here?


Whole schema look like this:
User generated imageSchema is as:
Radnik({mbr,prz,ime,plt,god,sef,sodel,srm},{mbr})
Projekat({spr,nap,nar,ruk},{spr})
Radproj({spr,mbr,brc},{spr+mbr})
Odeljenje({sodel,nazod,lok},{sodel})
Radnomesto({srm,naz},{srm})

and referential integrities are:
Radnik[sef]Radnik[mbr]
Radnik[sodel]Odeljenje[sodel]
Radnik[srm]Radnomesto[srm]
Projekat[ruk]Radnik[mbr]
Radproj[spr]Projekat[spr]
Radproj[mbr]Radnik[mbr]

And whole radnikprojekat-tabele.sql script for creating all tables is in attachment.
radnikprojekat-tabele.sql
ASKER CERTIFIED SOLUTION
Avatar of MikeOM_DBA
MikeOM_DBA
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of KPax
KPax

ASKER

Yes, you are right. It is very obvious.
I figured it out later, but left open question anyway.
Thank for answer.