2

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

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

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

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

4

3 回答 3

2

最一般的方法是

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
    )
于 2013-09-11T10:14:18.070 回答
1
SELECT DISTINCT name
FROM table1 NATURAL JOIN table2
WHERE table2.code = 
(SELECT CODE FROM RATE WHERE RATE=(SELECT MIN(RATE) FROM RATE))

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

于 2013-09-11T10:08:23.347 回答
0

尝试这个,

WHERE table2.code = (SELECT Code FROM rates ORDER BY rate LIMIT 1)
于 2013-09-11T10:02:22.307 回答