sql查询找到一个价格,用于范围之间的项目金额

时间:2010-11-05 06:58:24

标签: sql-server-2005

我有一个带字段的表

item_no  item_amount_from  item_amount_to price
101        200                  300        10
101        300                  400         20
101        400                  500         30
101        500                  null        40

如果项目金额介于(item_amount_from)之间,我想创建一个可以检索价格的查询 (item_amount_to)范围请让我知道我应该如何处理查询

1 个答案:

答案 0 :(得分:1)

看看这样的事情。

我会注意到你错过了开头的行。像101,null,200,5

这样的东西
DECLARE @Table TABLE(
        item_no INT,
        item_amount_from FLOAT,
        item_amount_to FLOAT,
        price FLOAT
)

INSERT INTO @Table SELECT 101,200,300,10 
INSERT INTO @Table SELECT 101,300,400,20 
INSERT INTO @Table SELECT 101,400,500,30 
INSERT INTO @Table SELECT 101,500,null,40

DECLARE @Amount FLOAT,
        @ItemNO INT

SELECT  @Amount = 510,
        @ItemNO = 101

SELECT  *
FROM    @Table
WHERE   item_no = @ItemNO
AND     (
                ((item_amount_from <= @Amount AND item_amount_to > @Amount))
            OR  (@Amount >= item_amount_from AND item_amount_to IS NULL)
            OR  (@Amount <= item_amount_to AND item_amount_from IS NULL)
        )