高分请教 SQL 查询语句
表中有字段 IDX(int),FREQ(float)
现在有如下记录:
1,10
2,11.2
3,18.4
4,47.4
5,50.9
6,85.7
......
现在我已知 FREQ=18。想在数据库中找到与它最接近的值即18.4的IDX---3.
用SQL语句怎么实现?
[解决办法]
declare @T table([IDX] int,[FREQ] float)
insert @T
select 1,10 union all
select 2,11.2 union all
select 3,18.4 union all
select 4,47.4 union all
select 5,50.9 union all
select 6,85.7
DECLARE @freq INT
SET @freq=18
select TOP 1 * from @T ORDER BY ABS([FREQ]-@freq)
/*
IDX FREQ
----------- ----------------------
3 18.4
*/
WITH a1 (IDX,FREQ) AS
(
SELECT 1,10 UNION all
SELECT 2,11.2 UNION all
SELECT 3,18.4 UNION all
SELECT 4,47.4 UNION all
SELECT 5,50.9 UNION all
SELECT 6,85.7
)
SELECT TOP 1 IDX
FROM a1
ORDER BY ABS(FREQ-18) asc