2010-11-05 82 views
0

我有場SQL查詢來發現

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

看看這樣的事情。

我會注意到,雖然你錯過了開幕行。像101,空,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) 
     ) 
+0

但它在存儲過程而言,不能我有一些直接查詢 – NoviceToDotNet 2010-11-05 07:06:40

+0

什麼的isNull在這個 – NoviceToDotNet 2010-11-05 07:09:58

+0

的IS空值cncept將是檢查的無界(500個),所以如果金額爲510. – 2010-11-05 08:07:06