【问题标题】:Extract and evaluate range from a give range string从给定的范围字符串中提取和评估范围
【发布时间】:2020-10-04 16:49:52
【问题描述】:

我有一张存储产品的表格。下面是带有数据的架构。

我想要实现的是我将 ProductId、Tenure 和 Range 作为参数传递,它会选择匹配的记录。

例如,如果我有我的参数 ProductId = 21Tenure=Duration=1Range =14678,那么它应该给我 Id=4 作为我的预期输出。因为范围是10001-15000。

【问题讨论】:

  • 旁白:Price_Range 实际上应该是两列,例如MinPriceMaxPrice。这样,它们都可以是合适的数字数据类型,您不必绕着诸如负值之类的问题跳舞,例如'-30 - -15',没有人预料到石油期货会受到打击。

标签: sql sql-server tsql sql-server-2017


【解决方案1】:

您可以将parsename()try_convert() 一起使用

示例

Declare @YourTable Table ([ID] varchar(50),[ProductID] int,[Price_Range] varchar(50),[Duration] int)
Insert Into @YourTable Values 
 (1,21,'0 - 5000',1)
,(2,21,'5001 - 10000',1)
,(4,21,'10001 - 15000',1)
,(5,21,'15001 - 20000',1)
 
Select * 
 From @YourTable
 Where ProductID = 21 
   and Duration  = 1
   and 14678 between try_convert(int,parsename(replace(Price_Range,'-','.'),2))
                 and try_convert(int,parsename(replace(Price_Range,'-','.'),1))
   

   

退货

ID  ProductID   Price_Range     Duration
4   21          10001 - 15000   1
  

注意:try_convert() 可能不是必需的。不了解数据的全部范围,最好避免误报。

【讨论】:

    【解决方案2】:

    我认为将parsename() 用于此类目的很恶心——很聪明,但也很恶心。 SQL Server 确实应该提供相应的功能。

    所以,我会使用:

    14678 >= try_convert(int, left(price_range, charindex(' ', price_range))) and
    14678 <= try_convert(int, stuff(price_range, 1, charindex('-', price_range) + 1, ''))
    

    【讨论】:

    • "icky" ...这是技术术语吗? :)
    • @JohnCappelletti。 . . .我也承认它很聪明。
    • 只是和你一起玩一点儿。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 2018-04-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2022-11-30
    相关资源
    最近更新 更多