【问题标题】:MYSQL selecting across multiple tables + using mathematical operators Average/CountMYSQL 跨多个表选择 + 使用数学运算符平均/计数
【发布时间】:2013-11-19 20:10:23
【问题描述】:

我有两个具有以下属性的表:

表:部门

dept_nbr

部门名称

部门电话

部门建筑

部门经理

表:员工

emp_nbr

emp_lname

emp_fname

emp_phone

emp_dateofbirth

emp_date_hired

emp_nbr_of_dependents

emp_dept

dept_nbr = emp_dept

我需要:

每个部门

1.) 总数。员工家属

2.) 平均数。的家属。 - 我猜是AVG

3.) 总数。员工人数 - 我猜是 count(*)

有人可以帮我解决这个问题吗?以下是我的代码

  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;

第二部分:

包括员工人数少于 50 人的部门

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 ;

我尝试了上述方法并收到错误 1111

谢谢大家

【问题讨论】:

  • 你所尝试的,你猜到的,你应用了什么
  • 您是否尝试过解决您面临的问题,或者您希望我们为您编写程序代码?
  • 我已经添加了到目前为止我尝试过的内容。它给了我输出..但我不知道它是否准确/最好的方法。感谢您查看问题

标签: mysql sql join


【解决方案1】:
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

【讨论】:

  • 谢谢..有没有其他办法不使用HAVING?
  • 也许嵌套选择还有其他方法,但为什么你想避免 HAVING?这是完美的常规 SQL 语法。
【解决方案2】:

更多的聚合功能可以一选组合。

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 部分在GROUP BY 之前应用,然后HAVING 应用在结果上。

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

【讨论】:

  • 谢谢..我知道有一种更有效的方法。结果是一样的,但这似乎是一个更好的方法。第二部分的任何建议..我的 where 语句不起作用。
  • 编辑答案以包含第二部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-09
  • 1970-01-01
  • 2021-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多