读书人

接近值

发布时间: 2013-11-08 17:52:14 作者: rapoo

相近值
各位大!我在查遇到个难题!如表中有 1,100,200,300 等数值,当使用10到表中查询时需要返回 1,260 时返回 200 都是要找等于或小于的行。请问大家有没有好的方法。 sql
[解决办法]

引用:
源数据
id a b
1 1 a56
2 100 b68
3 200 e98
4 300 f15
条件数据
id 条件
1 60
2 75
3 250
4 310
返回数据表
1 a56
2 a56
3 e98
4 f15
类似这样的操作


这样吗:

;with t(id ,a ,b)
as
(
select 1, 1, 'a56'
union all select 2, 100, 'b68'
union all select 3, 200, 'e98'
union all select 4, 300, 'f15'
),

condition(id, 条件)
as
(
select 1, 60
union all select 2 , 75
union all select 3 , 250
union all select 4 , 310
)

select tt.id,tt.b
from
(
select t.*,
row_number() over(partition by c.id,c.条件 order by t.a desc) as rownum
from t
inner join condition c
on t.a <= c.条件
)tt
where rownum = 1
/*
idb
1a56
1a56
3e98
4f15
*/

[解决办法]

create table 源数据
(id int,a int,b varchar(10))

insert into 源数据
select 1,1,'a56' union all
select 2,100,'b68' union all
select 3,200,'e98' union all
select 4,300,'f15'

create table 条件数据
(id int,条件 int)

insert into 条件数据
select 1,60 union all
select 2,75 union all
select 3,250 union all
select 4,310


select a.id,
(select top 1 b.[b]
from 源数据 b
where b.[a]<a.条件
order by b.id desc) 'bb'
from 条件数据 a

/*
id bb
----------- ----------
1 a56
2 a56
3 e98
4 f15

(4 row(s) affected)
*/

读书人网 >SQL Server

热点推荐