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

时间:2013-09-11 09:59:31

标签: sql min

我有一个SQL查询,用于使用子查询从不同的表中选择事物列表。我的目的是找到特定列中值最低的那些东西。

这是我目前的查询。我知道最低费率是350但我不能在我的查询中使用它。任何将其改为MIN(费率)的努力都没有成功。

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

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

3 个答案:

答案 0 :(得分:1)

SELECT DISTINCT name
FROM table1 NATURAL JOIN table2
WHERE table2.code = 
(SELECT CODE FROM RATE WHERE RATE=(SELECT MIN(RATE) FROM RATE))

考虑到您只期望一个最小值记录。

答案 1 :(得分:1)

最常用的方法是

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
    )

答案 2 :(得分:0)

试试这个,

WHERE table2.code = (SELECT Code FROM rates ORDER BY rate LIMIT 1)