我想解决的问题是:
列出薪水低于平均工资的所有员工,并列出多少。
问题中的表格:
CREATE TABLE Staff
(`staffNo` varchar(4), `fName` varchar(5), `lName` varchar(5),
`position` varchar(10), `sex` varchar(1), `DOB` varchar(9),
`salary` int, `branchNo` varchar(4))
;
INSERT INTO Staff
(`staffNo`, `fName`, `lName`, `position`, `sex`, `DOB`, `salary`, `branchNo`)
VALUES
('SL21', 'John', 'White', 'Manager', 'M', '1-Oct-45', 30000, 'B005'),
('SG37', 'Ann', 'Beech', 'Assistant', 'F', '10-Nov-60', 12000, 'B003'),
('SG14', 'David', 'Ford', 'Supervisor', 'M', '24-Mar-58', 18000, 'B003'),
('SA9', 'Mary', 'Howe', 'Assistant', 'F', '19-Feb-70', 9000, 'B007'),
('SG5', 'Susan', 'Brand', 'Manager', 'F', '3-Jun-40', 24000, 'B003'),
('SL41', 'Julie', 'Lee', 'Assistant', 'F', '13-Jun-65', 9000, 'B005')
;
我一直在努力的解决方案是:
SELECT s.staffNo, s.fName, s.lName, s.salary
FROM Staff s
WHERE s.salary < (SELECT AVG(s.salary) FROM *)
ORDER BY s.salary DESC;
然而,它没有回答问题的最后部分,“......并列出了多少。”
我曾经把它合并到这样:
SELECT staffNo, fName, lName, salary, (30000-salary) as Average
FROM Staff
WHERE salary < (SELECT AVG(salary) FROM Staff)
ORDER BY salary DESC;
但那只会出错......
您可以在此处提供任何帮助吗?
答案 0 :(得分:2)
加入一个返回平均薪水的子查询
SELECT staffNo, fName, lName, salary, avgSalary-salary AS salaryDiff, avgSalary
FROM Staff
JOIN (SELECT AVG(salary) AS avgSalary
FROM Staff) AS av
ON salary < avgSalary