mysql查询,以显示高于平均值的结果,该平均值在其总和中使用两个表

4sup72z8  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(285)

我想要一个只显示高于平均值的合同成本以及合同id的查询,我用以下内容创建我的平均值:

SELECT AVG(average_cost)
FROM (
SELECT SUM(contracts.hours*staff.rate) AS average_cost
FROM contracts
INNER JOIN staff ON contracts.staff_id = staff.staff_id
GROUP BY contracts.contract_id
) AS inner;

我想结果显示合同的id以及它的组,即使它显示的是所有合同的id以上的结果平均水平。只是很难让一个查询以高于平均值的方式显示结果,这个平均值比我习惯的要复杂得多。谢谢你的帮助。
edit*对于一些示例数据,表比这更复杂,但我希望这有助于理解

contracts

contract_id   hours   staff_id
55            30       10
45            25       11
43            30       12
41            12       11
67            20       12   
49            20       13

staff

staff_id   rate
10         50 
11         45
12         80
13         45

因此,上述项目的平均合同成本约为1344.167元。对于本例,我希望结果显示成本高于平均值的合同的合同id。

results

contract_id   
55            
43            
67
6ioyuze2

6ioyuze21#

我的例子可以帮助你:

SELECT first_name, last_name, invoice_amount
        FROM students 
        INNER JOIN invoices 
        ON students.id_student = invoices.id_student
        WHERE invoice_amount > (select avg(invoice_amount) from invoices)
v9tzhpje

v9tzhpje2#

据我所知,你的问题是,我认为你在寻找:

select contract_id
from contracts join staff on (contracts.staff_id = staff.staff_id)
where (hours*rate) > 
(select avg(hours*rate)
from contracts join staff on (contracts.staff_id = staff.staff_id)
)
kx7yvsdv

kx7yvsdv3#

这里有一种方法:

SELECT c.contract_id, SUM(c.hours*s.rate) AS cost
FROM contracts c INNER JOIN
     staff s
     ON c.staff_id = s.staff_id
GROUP BY c.contract_id
HAVING cost > (SELECT AVG(average_cost)
               FROM (SELECT SUM(c.hours*s.rate) AS average_cost
                     FROM contracts c INNER JOIN
                          staff s
                          ON c.staff_id = s.staff_id
                     GROUP BY c.contract_id
                    ) sc
               );

相关问题