SQL - 查找给定参数的最接近价格

时间:2011-10-12 10:14:41

标签: mysql sql database db2

我试图找到价格最接近SQL中给定参数的元组。 例如:参数price = 6将返回id 1和2。 参数price = 20将返回id 3。

表:

ID     PRICE
1      5
2      5
3      10

SELECT id 
FROM Table
WHERE table.price ?? 6

任何想法如何做到这一点?

谢谢。

4 个答案:

答案 0 :(得分:1)

SELECT ID
FROM TableX
WHERE PRICE = @CheckPrice +
      ( SELECT MIN(ABS(PRICE - @CheckPrice))
        FROM TableX
      )
   OR PRICE = @CheckPrice -
      ( SELECT MIN(ABS(PRICE - @CheckPrice))
        FROM TableX
      )

或(可能更好的表现):

SELECT ID
FROM 
    TableX
  CROSS JOIN
          ( SELECT 
                ( SELECT MIN(PRICE) - @CheckPrice
                  FROM TableX
                  WHERE PRICE >= @CheckPrice
                ) AS Pover 
              , ( SELECT @CheckPrice - MAX(PRICE)
                  FROM TableX
                  WHERE PRICE <= @CheckPrice
                ) AS Punder
            FROM dual
          ) AS tmp 
WHERE PRICE IN ( @CheckPrice + LEAST(Pover, Punder)
               , @CheckPrice - LEAST(Pover, Punder)
               )

答案 1 :(得分:1)

SELECT id, price
FROM thetable t1
WHERE NOT EXISTS ( SELECT *
   FROM thetable t2
   WHERE abs (t2.price - 6) < abs (t1.price - 6)
   );

答案 2 :(得分:1)

此查询使用子查询选择最接近的价格,然后返回与该价格匹配的所有行:

SELECT *
FROM Table
WHERE price = ( --could also use "WHERE price in" here...
    SELECT TOP 1 price FROM Table
    GROUP BY price
    ORDER BY Min(Abs(price - ?)))

答案 3 :(得分:0)

我们正在使用UNION子查询来获得最接近目标价格的价格。 在每个子查询中,我们得到绝对delta(每个模型价格和目标价格之间的差异)和ORDER BY delta。工作非常快速和稳定。希望它有所帮助;)

SET @CheckPrice = 3910;

(
    SELECT
        m_id,
        m_name,
        m_auto_price,
        m_auto_discount,
        ABS(m_auto_price - @CheckPrice)AS delta
    FROM
        s_models
    WHERE
        m_auto_price >= @CheckPrice
    ORDER BY
        m_auto_price ASC
    LIMIT 10
)
UNION
    (
        SELECT
            m_id,
            m_name,
            m_auto_price,
            m_auto_discount,
            ABS(m_auto_price - @CheckPrice)AS delta
        FROM
            s_models
        WHERE
            m_auto_price <= @CheckPrice
        ORDER BY
            m_auto_price DESC
        LIMIT 10
    )
ORDER BY
    delta ASC,
    m_auto_price DESC,
    m_auto_discount DESC