我有一个 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/