TSQL - 查找数字列表中数字的位置的有效方法?

时间:2011-05-17 21:41:06

标签: tsql

这似乎很简单;我必须直接错过一些东西。

TestTable的
Value1(int)
Value2(int)
Value3(int)
Value4(int)

插入TestTable 20,30,40,50中
值1 = 20
Value2 = 30
Value3 = 40
Value4 = 50

我有数字37.我想返回30和40(这两个数字之间有37个)。

使用TSQL的最有效方法是什么?

3 个答案:

答案 0 :(得分:1)

declare @TestTable table (Value1 int, Value2 int, Value3 int, Value4 int)
insert into @TestTable values (20, 30, 40, 50)

declare @Value int = 37

select
  case
    when @Value between Value1 and Value2 then Value1
    when @Value between Value2 and Value3 then Value2
    when @Value between Value3 and Value4 then Value3
    when @Value > Value4 then Value4
  end as Val1,   
  case
    when @Value < Value1 then Value1 
    when @Value between Value1 and Value2 then Value2
    when @Value between Value2 and Value3 then Value3
    when @Value between Value3 and Value4 then Value4
  end as Val2
from @TestTable  

结果:

Val1        Val2
----------- -----------
30          40

答案 1 :(得分:0)

SELECT TOP 1 [value] FROM TestTable WHERE [value] <= @number ORDER BY [value] DESC
UNION
SELECT TOP 1 [value] FROM TestTable WHERE [value] >= @number ORDER BY [value]

可选地

SELECT
  (SELECT TOP 1 [value] FROM TestTable WHERE [value] <= @number ORDER BY [value] DESC) AS [min],
  (SELECT TOP 1 [value] FROM TestTable WHERE [value] >= @number ORDER BY [value]) AS [max]

[value]字段上设置索引并检查您是否需要>= / <=>= / <个范围。

答案 2 :(得分:0)

你用一个包含你想要找到的值的变量替换34,但我认为这可以得到你想要的。

select
(select top 1 * from TestTable
where value > 34
order by value),

(select top 1 * from TestTable
where value < 34
order by value desc)