SQL 查询中的 MIN 函数 - 3 列访问

SQL MIN Function in a query - 3 columns Access

我尝试使用 min 函数,但当我尝试查看 3 列时它不起作用。 我有这个 table

并且在 Field_2 上使用 MIN() 函数,我想要得到这个输出

我的查询是

SELECT FIELD_1, MIN(FIELD_2) FROM TABLE GROUP BY FIELD_1

如果我添加列 ID,我得到的都是一样的 table。

改用subquery

select * 
from table t
where field_2 = (select min(field_2) from table where field_1 = t.field_1);

但是,您也可以使用 LIMIT 子句

select * 
from table t
where id = (select id
           from table 
           where field_1 = t.field_1
           order by field_2 asc
           LIMIT 1);

但是,有些 DBMS 没有 LIMIT 子句(SQL Srver),所以,使用 TOP 代替:

. . . 
where id = (select top (1) id
            from table 
            where field_1 = t.field_1
            order by field_2 asc);

你真的不需要聚合。您要过滤行。为此,我经常使用相关子查询:

select t.*
from t
where t.field2 = (select min(t2.field2) from t t2 where t2.field_1 = t.field_1);

当满足以下两个条件时,聚合最合适:

  • group by 子句指定您想要的行。 group by 键的每个组合都会产生一行。
  • 所有其他列将来自多行的值合并为一个值。

在您的情况下,第二个条件不成立。您需要特定行中的所有列。