我试图从部门表中获取每个部门,从员工表中获取富有和贫穷员工的数量。 到目前为止,我能够得到其中的一个,但似乎无法弄清楚如何为每个部门将富人和穷人写在两行上。
SELECT Depts.Department, IF (Employees.Salary>100000, 'Rich', 'Poor'),
COUNT(*) FROM `Employees`, `Depts`
WHERE Depts.Dept = Employees.Dept
GROUP BY Depts.Department
感谢您的帮助
最佳答案
最清晰的方法是合并结果;
SELECT Depts.Department, 'Poor', COUNT(*)
FROM `Employees`, `Depts`
WHERE Depts.Dept = Employees.Dept AND Employees.Salary <= 100000
GROUP BY Depts.Department
UNION
SELECT Depts.Department, 'Rich', COUNT(*)
FROM `Employees`, `Depts`
WHERE Depts.Dept = Employees.Dept AND Employees.Salary > 100000,
GROUP BY Depts.Department
关于MYSQL:根据if语句两次获取结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33380968/