SQL获取具有给定值或最接近值

时间:2016-06-16 12:54:29

标签: sql-server

我需要从查询中获取值等于参数的行或基于ID关闭的行。

ID          Value
----------- -----------
1           1
1           2
1           3
2           1
2           2
3           1

CREATE TABLE #Test (ID int, Value int)

INSERT INTO #Test VALUES (1,1)
INSERT INTO #Test VALUES (1,2)
INSERT INTO #Test VALUES (1,3)
INSERT INTO #Test VALUES (2,1)
INSERT INTO #Test VALUES (2,2)
INSERT INTO #Test VALUES (3,1) 

因此,对于值= 3,它应该返回

ID          Value
----------- -----------
1           3
2           2
3           1

对于ID = 1,我们有值3,而对于另一个,我想要的是与我给定输入3最接近的值。

编辑:

因此,对于value = 2,它应该返回

ID          Value
----------- -----------
1           2
2           2
3           1

4 个答案:

答案 0 :(得分:1)

只需使用GROUP BY上的ID对数据集进行分组,然后使用MAX获取最高值,并使用{{1}中提供的值限制数据像这样的子句:

WHERE

答案 1 :(得分:1)

这允许返回ID和Value以外的数据字段,这是使用group by时的限制。

 Declare @Param Int = 2

    ;With cteAssigned As
    (
    Select ID, Value, 
            Row_Number() Over (Partition By ID Order By Value Desc) SortOrder
        From #Test
        Where Value <= @Param
    )
    Select * From cteAssigned Where SortOrder = 1

没有CTE编辑 声明@Param Int = 2

Select * 
    From
        (
        Select ID, Value, 
                Row_Number() Over (Partition By ID Order By Value Desc) SortOrder
            From #Test
            Where Value <= @Param
        ) A
    Where SortOrder = 1

答案 2 :(得分:0)

    SELECT ID ,MAX(VALUE) VALUE FROM #TEST
    GROUP BY ID

DECLARE @ID INT = 3
SELECT ID ,MAX(VALUE) VALUE FROM #TEST
 WHERE ID <= @ID
GROUP BY ID

then this is also correct only 

答案 3 :(得分:0)

CREATE TABLE #Test (ID int, Value int)

INSERT INTO #Test VALUES (1,1)
INSERT INTO #Test VALUES (1,2)
INSERT INTO #Test VALUES (1,3)
INSERT INTO #Test VALUES (2,1)
INSERT INTO #Test VALUES (2,2)
INSERT INTO #Test VALUES (3,1) 

DECLARE @Value INT = 0

SELECT DISTINCT
       t.ID,
       ca_t.Value
FROM #Test t
CROSS APPLY
    ( SELECT TOP 1 t2.Value
      FROM #Test t2
      WHERE t2.ID = t.ID
      ORDER BY ABS(t2.Value - @Value)
    ) ca_t

所以只需将@Value更改为您正在寻找的价值。