在表格中查找平均值

时间:2014-10-16 22:14:05

标签: mysql sql

CREATE TABLE `departments` (
  `DEPARTMENT_ID` decimal(6,0) NOT NULL,
  `DEPARTMENT_NAME` varchar(30) CHARACTER SET utf8 NOT NULL,
  `MANAGER_ID` decimal(8,0) DEFAULT NULL,
  `LOCATION_ID` decimal(6,0) DEFAULT NULL,
  PRIMARY KEY (`DEPARTMENT_ID`),
  KEY `LOCATION_ID` (`LOCATION_ID`),
  CONSTRAINT `FK_departments_locations` FOREIGN KEY (`LOCATION_ID`) REFERENCES `locations` (`LOCATION_ID`)


CREATE TABLE `employees` (
  `EMPLOYEE_ID` decimal(8,0) NOT NULL,
  `FIRST_NAME` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
  `LAST_NAME` varchar(25) CHARACTER SET utf8 NOT NULL,
  `EMAIL` varchar(255) CHARACTER SET utf8 NOT NULL,
  `PHONE_NUMBER` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
  `HIRE_DATE` date DEFAULT NULL,
  `JOB_ID` varchar(10) CHARACTER SET utf8 NOT NULL,
  `SALARY` decimal(10,2) DEFAULT NULL,
  `COMMISSION_PCT` decimal(4,2) DEFAULT NULL,
  `MANAGER_ID` decimal(8,0) DEFAULT NULL,
  `DEPARTMENT_ID` decimal(6,0) DEFAULT NULL,
  PRIMARY KEY (`EMPLOYEE_ID`),
  KEY `DEPARTMENT_ID` (`DEPARTMENT_ID`),
  KEY `MANAGER_ID` (`MANAGER_ID`),
  KEY `JOB_ID` (`JOB_ID`),
  CONSTRAINT `FK_employees_departments` FOREIGN KEY (`DEPARTMENT_ID`) REFERENCES `departments` (`DEPARTMENT_ID`),
  CONSTRAINT `FK_employees_employees` FOREIGN KEY (`MANAGER_ID`) REFERENCES `employees` (`EMPLOYEE_ID`),
  CONSTRAINT `FK_employees_jobs` FOREIGN KEY (`JOB_ID`) REFERENCES `jobs` (`JOB_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

因此,在一个查询中,我如何找到员工平均工资大于或等于$ 10,000 的所有部门。名称应显示

到目前为止,我已经尝试了

SELECT DEPARTMENT_ID AS depts, SALARAY 
FROM bliu.employees 
WHERE salary >= 10000 
JOIN departments 
WHERE DEPARTMENT_ID = depts 

它不会工作

谢谢!

1 个答案:

答案 0 :(得分:1)

这是非常基本的SQL,我猜测练习的重点是使用GROUP BY ... HAVING语法。

SELECT 
  D.DEPARTMENT_NAME,                 -- what column to show
  AVG(E.SALARY) AS AverageSalary     -- strictly not needed, but nice to show
FROM DEPARTMENTS AS D                -- from what table, using an alias (D)
JOIN EMPLOYEES AS E                  -- join the emp table (E) to get salaries
ON D.DEPARTMENT_ID = E.DEPARTMENT_ID -- join on this condition (dept_id equality)
GROUP BY D.DEPARTMENT_ID             -- group the data by department
HAVING AVG(E.SALARY) >= 10000        -- and filter the groups
                                     -- for avg(salary) >= 10000