答案 0 :(得分:1)
在您的示例中,无法找到诸如 9.999 之类的值的折扣...该价格大于9.99且小于10,并且不适合放入其中您的任何范围。首先,将您的数据更改为:
| From | To | Discount |
|------|------|----------|
| 0 | 10 | 0.05 |
| 10 | 20 | 0.10 |
| 20 | 50 | 0.12 |
| 50 | NULL | 0.13 |
然后您可以像下面那样探查表:
SELECT Discount
FROM Discounts
WHERE (@Value >= [From])
AND (@Value < [To] OR [To] IS NULL)
答案 1 :(得分:1)
假设范围内没有差距,我发现在许多数据库中,最有效的方法是:
select t.*,
(select top 1 d.discount
from discounts d
where t.[$] <= d.[from$] -- the $ is for whatever column name you actually use
order by d.[from$] desc
) as discount
from t;
(请注意,这会忽略to$
。)
尤其是,这应该能够利用discounts(from$, discount)
上的索引。
答案 2 :(得分:0)
我们可以在此处尝试使用BETWEEN
SELECT
MAX(IIF(price BETWEEN FROM$ AND TO$, Discount, NULL)) AS Discount
FROM yourTable;
我们通常会期望您的折扣表可以存储多个组的信息,例如产品。在这种情况下,我们可以这样写:
SELECT
product,
MAX(IIF(price BETWEEN FROM$ AND TO$, Discount, NULL)) AS Discount
FROM yourTable
GROUP BY
product;