繁体   English   中英

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

[英]SQL selecting minimum value in a sub query when exact value is unknown

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

这是我目前拥有的查询。 我知道最低费用是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 = 
(SELECT CODE FROM RATE WHERE RATE=(SELECT MIN(RATE) FROM RATE))

考虑到您只希望获得一条最低记录。

最通用的方法是

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
    )

尝试这个,

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM