让我先告诉你我的样本数据结构。
CREATE TABLE foobar (
id int primary key,
lastname varchar(100) not null,
firstname varchar(100) not null,
val1 int not null,
val2 int not null
)
想象样本条目:
1, Smith, Bob, 1, 3
2, Smith, Bob 2, 1
3, SMith, Allen , 3, 4
即。姓氏,姓氏在这里并不明显
现在查看查询:
select lastname, firstname, avg(val1), avg(val2)
from foobar
where lastname = 'Smith'
group by firstname
示例输出:
1, Smith, Bob, 1.5 , 2
2, Smith, Allen , 3, 4
现在我想要三件事。
1. get me all smith where avg(val1) is the biggest value of all
2. get me all smith where avg(val1) is the lowest value of all
样品:
1. 1.5 is smallest value therefore get me Bob
2. 3 is the biggest value therefore get me Allen
我不知道如何有效地做到这一点。 我的方法是保存avg()的最小值和最大值,然后加入该值的同一个表。但我觉得这是一个糟糕的解决方案。
有一些有效的方法吗?
答案 0 :(得分:-1)
我不确定你的意思是什么。根据定义,平均值永远不会是最大值,而是所有的中值?
如果您只想返回表格中最大和最小的条目,请使用以下内容:
select lastname, firstname, max(val1), val2
from foobar
where lastname = 'Smith'
group by firstname
select lastname, firstname, min(val1), val2
from foobar
where lastname = 'Smith'
group by firstname