2

我有一个表格,上面有一些数值(直径)18 21 27 34 42 48 60 76 89 114 等...

例如,如果我在 text.box 中输入一个数字,我该如何选择最接近的值。25 选择 27, 100 选择 114, 48 选择 48。

我输入了以下代码,但它的行为不正确......它正在选择最接近的值,而不是 MAX 最接近的值:

strSQL = "SELECT * " & "FROM [materials] WHERE ABS([dia] - " & Me.TextBox1.Text & ") = (SELECT MIN(ABS([dia] - " & Me.TextBox1.Text & ")) FROM [materials])"

此代码位于连接到 DAO 数据库的 excel 用户表单中。

谢谢!

4

3 回答 3

2

假设您使用的是 SQL Server,您可以尝试类似

strSQL = "SELECT TOP 1 * " & "FROM [materials] WHERE [dia] >= " & Me.TextBox1.Text & " ORDER BY dia ASC"

如果是 MySQL 你将不得不使用LIMIT

LIMIT 子句可用于限制 SELECT 语句返回的行数。

于 2013-10-21T13:25:16.477 回答
2
strSQL = "SELECT TOP 1 * FROM materials " & _
         "WHERE dia >= " & Me.TextBox1.Text & " " & _
         "ORDER BY dia"
于 2013-10-21T13:24:31.413 回答
1

实际上,您的问题描述是错误的。
您不想要最接近的值,您想要大于或等于请求的最小值。

您实际要求的解决方案是:

DECLARE @fVal float
SET @fVal = 116 -- 114.5 -- 114.4 -- 114.6 

;WITH CTE AS
(
    SELECT 
          dia 
        ,(@fVal - dia) AS dist 
        ,ABS(@fVal - dia) AS absdist 
        ,SIGN(@fVal - dia) AS sig 
    FROM 
    ( 
        SELECT 18.0 AS dia 
        UNION SELECT 21.0 AS dia 
        UNION SELECT 27.0 AS dia 
        UNION SELECT 34.0 AS dia 
        UNION SELECT 42.0 AS dia 
        UNION SELECT 48.0 AS dia 
        UNION SELECT 60.0 AS dia 
        UNION SELECT 76.0 AS dia 
        UNION SELECT 89.0 AS dia 
        UNION SELECT 114.0 AS dia 
        UNION SELECT 115.0 AS dia 
    ) AS tempT 
) 

SELECT TOP 1 * FROM 
(
    SELECT * FROM CTE as cte2
    WHERE cte2.dist = (SELECT MAX(ct3.DIST) FROM CTE as ct3 WHERE sig = -1 )

    UNION 

    SELECT * FROM CTE as cte2
    WHERE cte2.dist = (SELECT MIN(ct3.DIST) FROM CTE as ct3 WHERE sig = 1) 


    UNION 

    SELECT * FROM CTE AS cte2 
    WHERE cte2.dist = 0 
) AS o

ORDER BY 

CASE WHEN dist = 0 
    THEN 0
    ELSE 1
END
,absdist, sig 
于 2013-10-21T14:00:24.253 回答