sql - 从 Table1 中查找值,其中 Table2 中的值位于 Table1 中的行之间

标签 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

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

谢谢。

最佳答案

对这样的事情感兴趣:

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

关于sql - 从 Table1 中查找值,其中 Table2 中的值位于 Table1 中的行之间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24095515/

相关文章:

sql - 在网络 PC 上找不到 SQL 实例名称

sql - 主表的明细记录计数

php - 在 Symfony 3 中使用 MS SQL

mysql - 在 SQL 中选择 Where inside if then else

mysql - 将表中的两个时间范围合并为一个

c# - SQL Server 相当于 Oracle 'table of integer'

sql-server - 使用多个 CTE

jquery - Hive 查询到组

sql - 在 SQL Server 2008 R2 中将数据写入二进制字段

sql - 根据另一个数据库的查询结果查询一个数据库