2014-06-07 20 views
3

假設以下結構:查找值,其中從表2的值是行之間在表1

項目

ItemId Price 
---------------- 
1000 129.95 
2000 49.95 
3000 159.95 
4000 12.95 

閾值

PriceThreshold Reserve 
------------------------ 
19.95   10 
100    5 
150    1 

-- PriceThreshold is the minimum price for that threshold/level 

我使用SQL Server 2008根據「PriceThreshold」中的項目價格落在何處返回「Reserve」。

實施例:

ItemId Reserve 
1000 5 
2000 10 
3000 1 

- 價格爲項目Id 4000是不低於最低的價格門檻所以應當從結果中排除更大。

理想情況下,我想只能使用一些直接的T-SQL,但如果我需要創建一個存儲過程來創建一個臨時表來存儲值,那很好。

Link to SQL Fiddle for schema

這晚,我想我的大腦關閉,所以任何幫助表示讚賞。

謝謝。

回答

5

感興趣的東西是這樣的:

select 
    ItemId, 
    (select top 1 Reserve 
    from Threshold 
    where Threshold.PriceThreshold < Items.Price 
    order by PriceThreshold desc) as Reserve 
from 
    Items 
where 
    Price > (select min(PriceThreshold) from Threshold) 

SQLFiddle

+0

太棒了。這工作。我知道有人可以幫助我解決疲勞的大腦。 – jared

0

一種方式去了解這是使用reserve爲範圍的下邊界,並使用lead解析功能,生成「下一個「下邊界,即上邊界。

一旦你完成了這一切,只需要考慮價格應該在兩個邊界之間的條件。不幸的是,between操作不處理null S,所以你需要使用一個有點沉重的條件來處理第一行和最後一行:

SELECT [ItemId], [Reserve] 
FROM Items 
JOIN (SELECT [PriceThreshold] AS [Bottom], 
       LEAD([PriceThreshold]) OVER (ORDER BY [PriceThreshold]) AS [Top], 
       [Reserve] 
     FROM [Threshold]) t ON 
       [Price] Between [Bottom] AND [Top] OR 
       ([Top] IS NULL AND [Price] > [Bottom]) OR 
       ([Bottom] IS NULL AND [Price] < [Top]) 

SQLFiddle solution

0

可以拿到較低以及綁定

select i.itemid, max(lo.pricethreshold) as lo 
from items i 
join threshold lo on lo.pricethreshold <= i.price 
group by i.itemid 

,並使用這個檢索儲備

with bounds as (select i.itemid, max(lo.pricethreshold) as lo 
       from items i 
       join threshold lo on lo.pricethreshold <= i.price 
       group by i.itemid) 
select i.itemid, t.reserve 
from items i 
join bounds b on b.itemid = i.itemid 
join threshold t on t.pricethreshold = b.lo 

SQLFiddle

相關問題