我正在尝试获得一个数字将落入的范围,例如,该范围将由表的列的值创建。让有一列'num1'包含数据(12,15,10,40,20,5)并且我给23作为数字进行搜索,然后我可以得到输出为'20和40'
我可以通过两个查询来获得所需的输出,但是我想要一个查询, 列将具有唯一值,因此,如果列值匹配,则范围将是数字及其最近的较小值,例如ex。如果输入为15,则输出将为12和15 列值:(12,15,10,40,20,5)搜索值:30个所需的输出:'20和40'
答案 0 :(得分:0)
也许这样的事情对您有利。使用LEAD()和LAG()窗口函数获取一行的上一个和下一个值。
DECLARE @T TABLE(Number INT)
INSERT @T VALUES(12),(15),(10),(40),(20),(5)
SELECT
Number,
NextNumber = ISNULL(LEAD(Number) OVER (PARTITION BY 1 ORDER BY Number),Number),
LastNumber = ISNULL(LAG(Number) OVER (PARTITION BY 1 ORDER BY Number),Number)
FROM
T
现在,从构建表中,您需要在可接受的范围内匹配输入并选择最佳匹配(在这种情况下,它是最接近范围开始/结束的位置)。
DECLARE @NumberToSearch INT =23
;WITH Ranges AS
(
SELECT
Number,
RangeStart = ISNULL(LAG(Number) OVER (PARTITION BY 1 ORDER BY Number) ,Number),
RangeEnd = ISNULL(LEAD(Number) OVER (PARTITION BY 1 ORDER BY Number) , Number)
FROM
@T
)
,ApplicableRanges AS
(
SELECT
Number,
RangeStart,
RangeEnd,
Instance = ROW_NUMBER() OVER(PARTITION BY 1 ORDER BY RangeStart)
FROM
Ranges R
WHERE
@NumberToSearch BETWEEN R.RangeStart AND R.RangeEnd
)
SELECT * FROM ApplicableRanges WHERE Instance = 1