简体   繁体   中英

MYSQL selecting across multiple tables + using mathematical operators Average/Count

I have two tables with the following attributes:

Table: Department

dept_nbr

dept_name

dept_phone

dept_building

dept_mgr

Table: Employee

emp_nbr

emp_lname

emp_fname

emp_phone

emp_dateofbirth

emp_date_hired

emp_nbr_of_dependents

emp_dept

dept_nbr = emp_dept

I need:

for each dept

1.) total no. of employee dependents

2.) average no. of dependents. - i am guessing AVG

3.) total no. of employees - i am guessing count(*)

Could someone please help me counter this?following is my code

  select DEPT_NAME, AVG(EMP_NBR_OF_DEPENDENTs), count(emp_fname) as Total_No_of_Employees from dept,employee where DEPT_NBR = EMP_DEPT group by DEPT_NAME;

second part:

include those departments that have fewer than 50 employees

select DEPT_NAME, AVG(EMP_NBR_OF_DEPENDENTs), count(emp_fname) as Total_No_of_Employees from dept,employee where DEPT_NBR in (select EMP_DEPT from employee where count(emp_fname)<50) group by DEPT_NAME ;

i tried the above and got an error 1111

Thanks Heaps

SELECT dept_name,SUM(emp_nbr_of_dependents),AVG(emp_nbr_of_dependents),COUNT(emp_nbr) 
FROM deptartment JOIN employee ON dept_nbr=emp_dept
GROUP BY dept_name
HAVING COUNT(emp_nbr)<50

More aggregation functions can be combined in one select.

select DEPT_NAME, 
  sum(EMP_NBR_OF_DEPENDENTs) employee_dependents_sum,
  AVG(EMP_NBR_OF_DEPENDENTs) avg_nbr_dependents, 
  count(emp_nbr) employee_count
from dept,employee 
where DEPT_NBR = EMP_DEPT 
group by DEPT_NAME
having employee_count < 50;

WHERE part is applied before GROUP BY and then HAVING is applied on result.

http://dev.mysql.com/doc/refman/5.5/en/select.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM