2016-11-28 94 views
2

我想顯示平均得分最高的工人姓名。 我的第一個表是worker表並存儲worker_id和worker_name。第二個表是測試表,並存儲誰參加測試的worker_id,test_id和標記。SQL查找最高平均得分的工人姓名

我的目標是能夠打印所有測試中平均得分最高的工作人員的姓名。這是我到目前爲止有:

select max(avg_mark) as max_avg 
    from (
     select worker_name, avg(mark) as avg_mark 
     from worker join test worker.worker_id = test.worker_id 
     group by worker_name 
     order by avg(mark) desc); 

但是,這僅返回最大平均分是誰有普通工人(S)的值,而不是姓名(或名稱)。如果我將worker_name添加到第一條select語句,並在底部添加一個由worker_name組成的組,那麼所有工作人員將返回平均值!

+0

見http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to- be-a-very-simple-sql-query – Strawberry

+0

請顯示錶格定義,樣本數據和預期輸出。 – OldProgrammer

回答

1

您已經關閉。這個想法是選擇平均匹配在單獨查詢中找到的最大值的工作人員。這裏有一個例子:

select master.worker_name, mx.max_mark 
from 
(select worker_name, avg(mark) as avg_mark 
from worker 
inner join test on worker.worker_id = test.worker_id 
group by worker_name) master 
inner join 
(select max(mark) as max_mark 
from test) mx 
on master.avg_mark = mx.max_mark 
+1

偉大而非常簡單,完美! – LEJ

3

一種選擇是使用CTE,然後使用最大窗口函數查詢它。

with cte as 
(
    select worker_name, avg(mark) as avg_mark 
    from worker join test worker.worker_id = test.worker_id 
    group by worker_name 
) 
select t.* 
from 
(
    select worker_name, avg_mark, max(avg_mark) over (partition by worker_name) max_mark 
    from cte 
) t 
where t.avg_mark = t.max_mark 
3
select  min(worker_name) keep (dense_rank last order by avg(mark)) 
from  worker join test worker.worker_id = test.worker_id 
group by worker_name 
; 
-1

因此,通過最大平均下降添加WORKER_NAME,訂購。然後將結果限制爲1.

+0

如果兩名工人都有最高的平均數? – LEJ