SQL使用行值范围选择记录

SQL使用行值范围选择记录,sql,sql-server,Sql,Sql Server,我有以下数据库记录 ID Weight Cost 1 3 1.00 2 10 2.00 3 14 3.00 我想要的是抓住给定重量的成本。因此,如果我的体重是5,成本将是2.00 首先,范围将是: Cost 1.00, weight 0-3 Cost 2.00, weight 4-10 Cost 3.00, weight 11-14 我不确定应该使用什么样的SQL来获取行范围,但通过使用列,我可以使用表1中的SE

我有以下数据库记录

ID    Weight    Cost
1     3         1.00
2     10        2.00
3     14        3.00
我想要的是抓住给定重量的成本。因此,如果我的体重是5,成本将是2.00

首先,范围将是:

Cost 1.00, weight 0-3
Cost 2.00, weight 4-10
Cost 3.00, weight 11-14
我不确定应该使用什么样的SQL来获取行范围,但通过使用列,我可以使用表1中的SELECT Cost,其中列1位于x和y之间


欢迎提出任何建议/意见。

这就是你想要的吗


有几种方法可以做到这一点,也许最简单的方法是根据表中的时间间隔生成一系列权重/成本。为了做到这一点,我们可以使用一个数字/理货表。在这种情况下,我使用的是master..spt_值表,它有一个合适的数字范围

因此,给出如下表格:

declare @t table (ID int, Weight int, Cost decimal(10,2))
insert @t values (1, 3, 1.00),(2, 10, 2.00),(3, 14, 3.00)
为了方便起见,我们可以定义封装在公共表表达式中的查询的两个版本。第一个版本使用lagwindow函数,需要比2012更新的SQL Server版本:

;with costs1 (weight, cost) as (
    select number, cost 
    from master..spt_values 
    inner join (
       select isnull(LAG(weight) over (order by id)+1,0) low, weight high, cost from @t 
    ) t on number <= t.high and number >= t.low
    where type= 'P'
)

select cost from costs1 where weight = 5;
另一种选择是只计算每个范围的低点/高点,并执行如下查询:

select cost from (
    select isnull(LAG(weight) over (order by id)+1,0) low, weight high, cost from @t
    ) t 
where 5 between low and high

通过上面的查询。

我没有得到逻辑。你能再解释一下吗?不清楚。扩展测试数据…你是说12应该返回2.00?在这种情况下,选择Top1。。。如果重量小于xxx,则应按重量说明订购work@JamesZ12将返回3.00,因为价格2.00时的最大权重为10。逻辑上似乎存在一些差异。对于5 OP想要得到1.00,您的查询将返回2。00@GiorgiNakeuri他也是。在这种情况下,我不理解他试图实现的逻辑啊,OP现在改变了。5返回2。
;with costs2 (weight, cost) as (
    select number, cost
    from master..spt_values 
    inner join (
       select 
       isnull(t2.weight + 1,0) as low, 
       t1.Weight as high, 
       t1.Cost 
    from @t t1 
    left join @t t2 on t1.ID - 1 = t2.ID 
    ) t on number <= t.high and number >= t.low
    where type= 'P'
    )

select cost from costs2 where weight = 5
select cost from (
    select isnull(LAG(weight) over (order by id)+1,0) low, weight high, cost from @t
    ) t 
where 5 between low and high