我有一张表,其中有一列有QTY范围,如1-5,6-9等,另一列有价格。即
Price QTY ------------------------ Price Qty Range ----- ---------- 45 1-5 35 6-9 30 10-18
现在我想从数量为7的表中得到结果因此返回的价格应为35(因为数量7在6-9范围内
任何有助于大力推荐的帮助
答案 0 :(得分: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
答案 1 :(得分:2)
如果您无法重新设计表格,那么您可以使用几个CTEs将其重新构建为此查询的合理表格:
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
。