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

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

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

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

表1:员工

  1. +------+-----------+-----------+-------------+-------------+--------+----------+
  2. | ID | LastName | FirstName | Location | Title | Gender | salaries |
  3. +------+-----------+-----------+-------------+-------------+--------+----------+
  4. | 1100 | Johnson | James | Chicago | Account Rep | M | 2000 |
  5. | 1200 | Smith | Sam | Chicago | Account Rep | M | 3000 |
  6. | 1300 | Mage | Sydney | Boston | Account Rep | F | 4000 |
  7. | 1400 | Engl | Beth | Dallas | Account Rep | F | 2500 |
  8. | 1500 | Ali | Tyler | Miami | Account Rep | M | 3500 |
  9. | 1600 | Rubin | Patricia | Los Angeles | Account Rep | F | 4400 |
  10. | 1700 | Childress | Rubin | Los Angeles | Account Rep | M | 1500 |
  11. +------+-----------+-----------+-------------+-------------+--------+----------+

表2:位置

  1. +-------------+----------------+-----------+
  2. | Location | Headquarters | Code |
  3. +-------------+----------------+-----------+
  4. | Dallas | No | 12 |
  5. | Los Angeles | Yes | 10 |
  6. | Chicago | No | 11 |
  7. | Denver | Yes | 10 |
  8. | Miami | Yes | 10 |
  9. +-------------+----------------+-----------+
zynd9foi

zynd9foi1#

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

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

相关问题