1

我有一张表,其中有一列的数量范围为 1-5、6-9 等,另一列中的价格。IE

价格 数量
----------------------
价格数量范围
----- ----------
45 1-5
35 6-9
30 10-18

现在我想从 Qty 为 7 的表中获取结果,因此返回的价格应该是 35(因为 Qty 7 在 6-9 范围内

任何帮助都非常感谢

4

2 回答 2

3

尝试这个 :-

  Declare @val int
  Set @val=7

 ;with cte(price,startVal,endVal) as
  ( Select price,
    parsename(replace([Qty Range],'-','.'),2),
    parsename(replace([Qty Range],'-','.'),1)
    from yourTable
  )
  Select Price from cte 
  where @val between startVal and endVal

结果 :35

SQL FIDDLE中的演示

于 2013-04-22T09:58:58.993 回答
2

如果您无法将表重新设计为健全,则可以使用几个CTE将其重建为该查询的健全表:

declare @PriceRanges table (Price int,QtyRange varchar(20))
insert into @PriceRanges (Price,QtyRange) values
(45,'1-5'),
(35,'6-9'),
(30,'10-18')

declare @Search int
set @Search = 7

;with FoundDashes as (
    select Price,QtyRange,CHARINDEX('-',QtyRange) as DashPos
    from @PriceRanges
)
, SaneRanges as (
    select Price,CONVERT(int,SUBSTRING(QtyRange,1,DashPos-1)) as LowRange,CONVERT(int,SUBSTRING(QtyRange,DashPos+1,8000)) as HighRange
    from FoundDashes
)
select Price from SaneRanges where @Search between LowRange and HighRange

结果产生35

于 2013-04-22T09:53:01.897 回答