mysql组合查询/从其他查询中减去1

iovurdzv  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(453)

嗨,在mysql中,我试图得到在总部工作的女性客户代表和不在总部工作的女性客户代表之间的平均工资差异。
我试过几种不同的方法,但我想不通。到目前为止,我的情况是:

SELECT avg(employees.salaries)
FROM employees
inner join location
on employees.location = location.location
WHERE gender = 'F' AND title = 'account rep'

表1:员工

+------+-----------+-----------+-------------+-------------+--------+----------+
|  ID  | LastName  | FirstName |  Location   |    Title    | Gender | salaries |
+------+-----------+-----------+-------------+-------------+--------+----------+
| 1100 | Johnson   | James     | Chicago     | Account Rep | M      |     2000 |
| 1200 | Smith     | Sam       | Chicago     | Account Rep | M      |     3000 |
| 1300 | Mage      | Sydney    | Boston      | Account Rep | F      |     4000 |
| 1400 | Engl      | Beth      | Dallas      | Account Rep | F      |     2500 |
| 1500 | Ali       | Tyler     | Miami       | Account Rep | M      |     3500 |
| 1600 | Rubin     | Patricia  | Los Angeles | Account Rep | F      |     4400 |
| 1700 | Childress | Rubin     | Los Angeles | Account Rep | M      |     1500 |
+------+-----------+-----------+-------------+-------------+--------+----------+

表2:位置

+-------------+----------------+-----------+
|  Location   | Headquarters   |      Code |
+-------------+----------------+-----------+
| Dallas      | No             |        12 |
| Los Angeles | Yes            |        10 |
| Chicago     | No             |        11 |
| Denver      | Yes            |        10 |
| Miami       | Yes            |        10 |
+-------------+----------------+-----------+
zynd9foi

zynd9foi1#

你的问题很清楚。聚合函数中只需要条件逻辑:

select
    avg(case when l.headquarters = 'Yes' then salaries end)
    - avg(case when l.headquarters = 'No' then salaries end) avg_diff
from employees e
inner join locations l on l.location = e.location
where e.gender = 'F' and e.title = 'Account Rep'

相关问题