Sql 查找表1中的值,其中表2中的值位于表1中的行之间

Sql 查找表1中的值,其中表2中的值位于表1中的行之间,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,假设以下结构: 项目: 阈值: 我正在使用SQLServer2008根据“PriceThreshold”中的商品价格介于两者之间的位置返回“Reserve” 例如: ItemId Reserve 1000 5 2000 10 3000 1 -ItemId 4000的价格不大于最低价格阈值,因此应将其从结果中排除 理想情况下,我只希望能够使用一些直接的T-SQL,但是如果我需要创建一个存储过程来创建一个临时表来存储值,那就好了 已经很晚了,我想我的大脑已经关闭了,所以我非常感

假设以下结构:

项目:

阈值:

我正在使用SQLServer2008根据“PriceThreshold”中的商品价格介于两者之间的位置返回“Reserve”

例如:

ItemId  Reserve
1000    5
2000    10
3000    1
-ItemId 4000的价格不大于最低价格阈值,因此应将其从结果中排除

理想情况下,我只希望能够使用一些直接的T-SQL,但是如果我需要创建一个存储过程来创建一个临时表来存储值,那就好了

已经很晚了,我想我的大脑已经关闭了,所以我非常感谢你的帮助


谢谢。

对以下内容感兴趣:

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)

一种方法是使用保留作为范围的下边界,并使用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])

您可以使用

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

令人惊叹的成功了。我知道有人能帮我摆脱疲惫的大脑。
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