我写了一个SQL语句来显示department_id,job_id和薪水最低的员工,但其中一个条件要求我排除名称为'IT'和'SALES'的部门,这些部门只能从另一个表部门。因此,我使用共享列department_id加入了两个表,并设法根据需要过滤结果,但是,我无法选择department_id与job_id和工资一起显示。这就是我到目前为止所做的:
SELECT EMPLOYEES.DEPARTMENT_ID JOB_ID, MIN(SALARY)
FROM EMPLOYEES JOIN DEPARTMENTS
ON DEPARTMENTS.DEPARTMENT_ID = EMPLOYEES.DEPARTMENT_ID
WHERE JOB_ID NOT LIKE '%REP'
AND DEPARTMENTS.DEPARTMENT_NAME NOT IN ('IT','SALES')
GROUP BY EMPLOYEES.DEPARTMENT_ID
HAVING MIN(SALARY) >= 6000 AND MIN(SALARY) <= 18000;
答案 0 :(得分:2)
首先,表别名使查询更容易编写和读取:
SELECT e.DEPARTMENT_ID, e.JOB_ID, MIN(e.SALARY)
FROM EMPLOYEES e JOIN
DEPARTMENTS d
ON d.DEPARTMENT_ID = e.DEPARTMENT_ID
WHERE e.JOB_ID NOT LIKE '%REP' AND d.DEPARTMENT_NAME NOT IN ('IT',' SALES')
GROUP BY e.DEPARTMENT_ID, e.JOB_ID
HAVING MIN(e.SALARY) >= 6000 AND MIN(e.SALARY) <= 18000;
您需要GROUP BY
中的所有非汇总列。
答案 1 :(得分:1)
SELECT中的部门ID后,查询中缺少逗号 - 因此它将部门ID的作业ID视为别名,并在查询结果中显示为作业ID。但是,您再次在GROUP BY子句中没有作业ID,需要在组中添加或必须使用任何聚合函数
SELECT **EMPLOYEES.DEPARTMENT_ID, JOB_ID,** MIN(SALARY)
FROM EMPLOYEES JOIN DEPARTMENTS ON DEPARTMENTS.DEPARTMENT_ID=EMPLOYEES.DEPARTMENT_ID
WHERE JOB_ID NOT LIKE '%REP' AND DEPARTMENTS.DEPARTMENT_NAME NOT IN('IT','SALES')
GROUP BY EMPLOYEES.DEPARTMENT_ID,JOB_ID
HAVING MIN(SALARY) >= 6000 AND MIN(SALARY) <= 18000;