假设一个表'雇员':
表员工
[id|name|department|sex|salary]
有没有办法显示男性员工最低工资等于或高于最高女性员工工资的所有部门?
这是一个让我很难理解的练习。我知道会有GROUP BY条款,但我真的不知道它们是如何工作的。
在MSSQL语法中首选的答案,如果它很重要的话。
答案 0 :(得分:1)
我不是由Mgmt Studio来验证它,但我认为这会为您提供所需的信息:
WITH cte AS (
SELECT
department,
min(case when sex = 'M' then salary else 10000000000) as MinMaleSalary,
max(case when sex = 'F' then salary else 0) as MaxFemaleSalary
FROM
Employees
GROUP BY department
)
SELECT *
FROM cte
WHERE MinMaleSalary >= MaxFemaleSalary;
如果这不起作用,你可以使用第二个cte分别获得Min Male和Max Female,然后再进行比较。
答案 1 :(得分:1)
也可以使用以下语句
select
a.*, b.minM
from
(
select
department, max(salary) maxF
from employees
where sex = 'F'
group by department
) A,
(
select
department, min(salary) minM
from employees
where sex = 'M'
group by department
) B
where a.Department = B.department and maxF <= minM