从Table1中查找值,其中Table2的值在Table1中的行之间

时间:2014-06-07 08:50:42

标签: sql sql-server sql-server-2008

假设以下结构:

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'之间的位置。

示例:

ItemId  Reserve
1000    5
2000    10
3000    1

- ItemId 4000的价格不高于最低价格阈值,因此应从结果中排除。

理想情况下,我希望能够使用一些直接的T-SQL,但是如果我需要创建一个存储过程来创建临时表来存储可能没问题的值。

Link to SQL Fiddle for schema

已经很晚了,我认为我的大脑已关闭,所以任何帮助都会受到赞赏。

感谢。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

解决此问题的一种方法是使用reserve作为范围的下边界,并使用lead分析函数生成“下一个”下边界,即顶部边界。

一旦你完成了这个,只需加入价格应该在两个边界之间的条件。不幸的是,between运算符无法处理null,因此您需要使用一些有点笨重的条件来处理第一行和最后一行:

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

答案 2 :(得分: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