我有一张桌子Employee
,
_________________________________
Id | name | salary
______________________________
1 | John | [1300 - 2000]
_______________________________
2 | Aby | [600 - 1000]
________________________________
3 | Mike | [1000 - 1500]
薪水栏为Nvarchar
我想要SQL中的Query / Function / SP,如果我搜索1400,则输出应如下所示
Id | name | salary
________________________________
1 | John | [1300 - 2000]
_______________________________
3 | Mike | [1000 - 1500]
谢谢。
答案 0 :(得分:1)
您不应将范围存储在一列中。但是,如果您无法更改它,那将是一种幻想:
SELECT [Id] , name,
,[salary]
FROM [Test Database].[dbo].[test] where
1700 >= RTRIM(LTRIM(SUBSTRING(salary,0, CHARINDEX('-',salary))))
and 1700 <= RTRIM(LTRIM(SUBSTRING(salary, CHARINDEX('-', salary) + 1, LEN(salary))))
答案 1 :(得分:1)
您需要提取数字值,然后转换为数字类型:
declare @mySalary money;
set @mySalary = 1400;
with Employee(ID, Name, Salary ) as
(
select 1,'John','[1300 - 2000]' union all
select 2,'Aby','[600 - 1000]' union all
select 3,'Mike','[1000 - 1500]'
), e2 as
(
select SUBSTRING(Salary,PATINDEX('%[0-9]%', Salary),CHARINDEX('-',Salary)-2) as Salary1,
SUBSTRING(Salary,CHARINDEX('-',Salary)+1,CHARINDEX(']',Salary)-CHARINDEX('-',Salary)-1) as Salary2,
e.*
from Employee e
)
select ID, Name, Salary
from e2
where @mySalary between cast(Salary1 as money) and cast(Salary2 as money);
ID Name Salary
1 John [1300 - 2000]
3 Mike [1000 - 1500]
答案 2 :(得分:1)
尝试此查询:
declare @tbl table (id int, name varchar(15), salary varchar(20));
declare @mySalary int = 1400;
insert into @tbl
select 1,'John','[1300 - 2000]' union all
select 2,'Aby','[600 - 1000]' union all
select 3,'Mike','[1000 - 1500]'
select id, name, salary from (
select id, name, salary,
convert(int, substring(salary, openBrcktIdx + 1, hyphenIdx - openBrcktIdx - 2)) lowerBound,
convert(int, substring(salary, hyphenIdx + 2, closeBrcktIdx - hyphenIdx - 2)) upperBound
from (
select *,
charindex('-', salary) hyphenIdx,
charindex('[', salary) openBrcktIdx,
charindex(']', salary) closeBrcktIdx
from @tbl
) t
) t where @mySalary between lowerBound and upperBound
答案 3 :(得分:1)
声明@ var1 int = 1400
选择*从 (选择*,replace(SUBSTRING(salary,0,CHARINDEX('-',salary,0)),'[','')作为Splitted1, replace(SUBSTRING(salary,CHARINDEX('-',salary,0)+ 1,len(salary)-1),']','')as Splitted2 来自员工 )作为t1 其中@ var1> = Splitted1和@ var1 <= Splitted2