我有一个具有以下结构的表:
id | workerID | materialID | date | materialGathered
不同的工人每天贡献不同数量的不同材料。一个工人每天只能做一次,但不一定每天都有。
我需要做的是弄清楚哪一个是最有效率的,哪一个是效率最低的,而它应该被测量为每天收集的AVG()材料。
老实说,我不知道该怎么做,所以我会感激任何帮助。
EDIT1:
一些示例数据
1 | 1 | 2013-01-20 | 25
2 | 1 | 2013-01-21 | 15
3 | 1 | 2013-01-22 | 17
4 | 1 | 2013-01-25 | 28
5 | 2 | 2013-01-20 | 23
6 | 2 | 2013-01-21 | 21
7 | 3 | 2013-01-22 | 17
8 | 3 | 2013-01-24 | 15
9 | 3 | 2013-01-25 | 19
说实话,输出看起来并不重要。也许是这样一个简单的表:
workerID | avgMaterialGatheredPerDay
我并没有真正尝试任何事情,因为我真的不知道,哈哈。
EDIT2:
考虑表格中的任何时间段(从表格的最早到最晚)。
此刻材料无关紧要。只有materialGathered列中的任意单位才有意义。
答案 0 :(得分:1)
在你的评论中,你说我们看看每个工人并考虑他们的平均日常工作技能,而不是检查在给定时间内最有效的工作,答案很简单:按工人分组以获得每个工人的结果记录,使用AVG获得他们的平均金额:
select workerid, avg(materialgathered) as avg_gathered
from work
group by workerid;
现在是最好和最差的工人。这些可以超过两个。所以你不能只记录第一个或最后一个记录,但需要知道最大和最小avg_gathered。
select max(avg_gathered) as max_avg_gathered, min(avg_gathered) as min_avg_gathered
from
(
select avg(materialgathered) as avg_gathered
from work
group by workerid
);
现在加入两个查询,以获得最低或最高的所有工作人员:
select work.*
from
(
select workerid, avg(materialgathered) as avg_gathered
from work
group by workerid
) as worker
inner join
(
select max(avg_gathered) as max_avg_gathered, min(avg_gathered) as min_avg_gathered
from
(
select avg(materialgathered) as avg_gathered
from work
group by workerid
)
) as worked on worker.avg_gathered in (worked.max_avg_gathered, worked.min_avg_gathered)
order by worker.avg_gathered;
还有其他方法可以做到这一点。例如,使用HAVING avg(materialgathered) IN (select min(avg_gathered)...) OR avg(materialgathered) IN (select max(avg_gathered)...)
而不是联接。然而,连接非常有效,因为你只需要一个选择最小和最大。