SQL查询以将特定列与相同列的平均值进行比较

时间:2018-08-27 06:05:41

标签: mysql sql

我的架构如下

doctor (doctor_name, residence_address, postal_code, year_experience) 
works (doctor_name, branch_name, annual_pay) 
branch (branch_name, branch_address, postal_code) 
patient (patient_name, doctor_name, branch_name) 

我被要求找回 doctor_name ,该医生的年薪高于名为“新加坡”的分支机构名称中所有医生的平均工资。

如何在sql查询中执行此操作。我正在使用MySQL,到目前为止,我已经尝试过了

SELECT doctor.doctor_name, doctor.residence_address
FROM doctor INNER JOIN works on doctor.doctor_name = works.doctor_name
WHERE avg(annual_pay)< annual pay

3 个答案:

答案 0 :(得分:2)

请尝试以下查询:

SELECT doctor_name
FROM doctor
INNER JOIN works ON doctor.doctor_name = works.doctor_name
WHERE annual_pay > (
        SELECT avg(annual_pay)
        FROM works
        )
    AND branch_name = 'Singapore'

答案 1 :(得分:0)

一种可能的解决方案是

select doctor_name 
from 
    works,
    (select avg(annual_pay) ap from works where branch_name='Singapore') ap
where
    annual_pay>ap.ap

答案 2 :(得分:0)

只需将薪水与子查询中计算出的平均值进行比较

SELECT doctor_name, annual_pay
FROM works 
WHERE annual_pay > (SELECT AVG(annual_pay) 
                    FROM works 
                    WHERE branch_name = 'Singapore') 
  AND branch_name = 'Singapore'