用于插入和获取范围到长度的价格的SQL查询

本文关键字:SQL 查询 插入 获取 范围 用于 | 更新日期: 2023-09-27 18:09:30

假设我有一个长度范围,它有不同的价格

Length      Price
0 - 10        18
11 - 15       20
16 - 20       30
21 - 40       45
41 - infinity 60

我该如何将这些信息存储在数据库中?当我输入10.625的长度时,我该如何检索这些信息?我怎样才能得到长度为10.625的商品的价格?


我不确定我是否已经解决了这个问题

priceData.Length_End = Math.Ceiling(priceData.Length);
        string selectStatement = 
            "SELECT Price PriceList2 " +
            "WHERE @Length_End >= Length_Start AND @Length <= Length_End";

然后我得到第一个阅读器的值

SqlDataReader reader = selectCommand.ExecuteReader();
while (reader.Read())
{
   price = decimal.Parse(reader["Price_Per_Ton"].ToString());
   break;
}
reader.Close();
如果我说错了,请纠正我。感谢所有的回复!

用于插入和获取范围到长度的价格的SQL查询

您可以将结构更改为:

len_start    len_end      price
0            10           18
11           15           20
16           20           30
21           40           45
41           infinity     60

并运行如下查询:

declare @len decimal
set @len= 10.615
select price from table
Where len_start <= @len and @len < len_end

如果你要使用NULL作为无穷大,运行这个查询:

select price from table
Where (len_end is not null AND len_start <= @len and @len < len_end) OR 
      (len_end is null AND len_start <= @len)

,我相信你只需要存储Length,当你想在你的查询中获得Price列时,你可以使用BETWEEN

;
Select Price
From YourTable
Where Length BETWEEN 11 AND 15

这是SQL Fiddle Demo

但是这种结构只有在知道每个范围的Length的最大值和最小值时才可以。如果您也想将它们存储在数据库中,您应该将Length列分开两个不同的列。

;
Max_Length | Min_Length | Price
0          | 10         | 18
11         | 15         | 20 
16         | 20         | 30
21         | 40         | 45
41         |            | 60

Select Price
From YourTable
Where Min_Length < 10.625 AND Max_Length > 10.625