表1
ID Value
001 100
002 125
003 150
004 175
005 200
006 225
...
预期产出
如果用户输入介于125到149之间的值,则ID应显示002
如果用户输入介于200到224之间的值,则ID应显示005
如何查询上述情况。
需要查询帮助
答案 0 :(得分:3)
将查询写入转换表(如ID,ValueFrom,ValueTo。
)会更容易对于此表:
SELECT MAX(ID)
FROM Table1
WHERE Value <= @value
基本上,如果输入155,则返回ID 1 2和3,然后获取MAX ID(3),这是答案。
答案 1 :(得分:2)
获取最接近的匹配并返回先前按值排序的第一行:
select top 1 id
from range
where value <= @value
order by value desc
或者,如果您需要将此查询合并到另一个:
select id
from range
where value = (select max(value) from range where value <= @value)
答案 2 :(得分:2)
你走了:
首先创建测试表:
CREATE TABLE #Temp(ID INT, Val INT)
INSERT INTO #Temp VALUES(1, 100);
INSERT INTO #Temp VALUES(2, 125);
INSERT INTO #Temp VALUES(3, 150);
INSERT INTO #Temp VALUES(4, 175);
INSERT INTO #Temp VALUES(5, 200);
INSERT INTO #Temp VALUES(6, 225);
设置测试值
DECLARE @value INT
SET @value = 125
如果ID是连续的(即1,2,3,4,5等)
SELECT t1.id
FROM #Temp t1, #Temp t2
WHERE t1.ID = t2.ID -1
AND @value BETWEEN t1.Val AND t2.Val -1
如果ID不是顺序的(即1,2,5,7,8等)
;WITH cte AS (SELECT ROW_NUMBER() OVER (ORDER BY id) AS rownum, ID, Val FROM #Temp)
SELECT t1.id
FROM cte t1, cte t2
WHERE t1.rownum = t2.rownum -1
AND @value BETWEEN t1.Val AND t2.Val -1
答案 3 :(得分:0)
在SELECT语句中使用CASE ....
例如:
declare @c int;
set @c=120;
SELECT
CASE
WHEN @c BETWEEN 100 AND 124 THEN '001'
WHEN @c BETWEEN 125 AND 149 THEN '002'
ELSE 'Other'
END