当确切值未知时,SQL 在子查询中选择最小值

标签 sql min

我有一个 SQL 查询,旨在使用子查询从不同的表中选择内容列表。我的目的是找到特定列中值(value)最低的那些东西。

这是我目前的查询。我知道最低费率为 350,但我无法在查询中使用它。任何将其更改为 MIN(rate) 的努力均未成功。

  SELECT DISTINCT name
  FROM table1 NATURAL JOIN table2
  WHERE table2.code = (SELECT Code FROM rates WHERE rate = '100')

如何更改该子查询以找到最低费率?

最佳答案

最通用的方法是

select distinct name
from table1 natural join table2
where
    table2.code in
    (
        select t.Code
        from rates as t
        where t.rate in (select min(r.rate) from rates as r)
    )

如果你有窗口函数,你可以使用rank()功能:

...
where
    table2.code in
    (
        select t.Code
        from (
            select r.Code, rank() over(order by r.rate) as rn
            from rates as r
        ) as t
        where t.rn = 1
    )

在 SQL Server 中,您可以使用 top ... with ties语法:

...
where
    table2.code in
    (
        select top 1 with ties r.Code
        from rates as r
        order by r.rate
    )

关于当确切值未知时,SQL 在子查询中选择最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18738135/

相关文章:

mysql - 使用特定参数选择下一个和上一个 id

mysql - LPAD/RPAD : Align column

r - 如何提取具有最小值或最大值的行?

c - 表中的最小值和最大值

c - 如何修复我的最大输出以及如何添加最大和最小数量

php - 如何在 PHP 中将 printf 添加到成功的查询返回中

mysql - 将用于检索值以进行比较的子查询合并到单个查询中?

sql - 范围通配符模式匹配行为与区分大小写的排序规则

c++ - 函数不返回输入数组的最高值和最低值

MySQL - 在 MAX 时间戳上左连接