相近數值

化境者 2013-11-05 09:23:54
各位大俠!我在寫查詢時遇到个难题!如表中有 1,100,200,300 等数值,当使用10到表中查询时需要返回 1,260 时返回 200 都是要找等于或小于的行。请问大家有没有好的方法。
...全文
234 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
Andy238 2013-11-05
  • 打赏
  • 举报
回复
select t1.b from Table t1,(select min(a) as a2 from Table where a<=条件) as t2 where t1.a=t2.a2
Andy238 2013-11-05
  • 打赏
  • 举报
回复
select t1.b from Table t1,(select min(a) as a2 from Table where a<=条件) as t2 where t1.a=t2.a
LongRui888 2013-11-05
  • 打赏
  • 举报
回复
引用 8 楼 lincanjin 的回复:
源数据 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
/*
id	b
1	a56
1	a56
3	e98
4	f15
*/
化境者 2013-11-05
  • 打赏
  • 举报
回复
源数据 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 类似这样的操作
LongRui888 2013-11-05
  • 打赏
  • 举报
回复
是这样吗:

CREATE TABLE temp (i int)
INSERT temp
SELECT 1 UNION 
SELECT 100 UNION 
SELECT 200 UNION 
SELECT 300


declare @i int

set @i = 260

SELECT max(i) FROM temp 
WHERE i<= @i 
/*
200
*/
LongRui888 2013-11-05
  • 打赏
  • 举报
回复
能不能给点具体的数据,然后需要返回怎样的结果,哪些字段 都贴出来呢
Shawn 2013-11-05
  • 打赏
  • 举报
回复
SELECT TOP(1) * 
FROM dbo.tablename
WHERE ID <= @ID
ORDER BY ID DESC
华为黑名单 2013-11-05
  • 打赏
  • 举报
回复
你是不是想要这样的数据 给传入条件 取出小于传入参数最大的整数?
lzw_0736 2013-11-05
  • 打赏
  • 举报
回复

CREATE TABLE #temp (i int)
INSERT #temp
SELECT 1 UNION 
SELECT 100 UNION 
SELECT 200 UNION 
SELECT 300

SELECT TOP 1 * FROM #temp WHERE i<=10 ORDER BY i DESC

SELECT TOP 1 * FROM #temp WHERE i<=260 ORDER BY i DESC
华为黑名单 2013-11-05
  • 打赏
  • 举报
回复
SELECT MAX(Score) FROM dbo.Test WHERE score < 10
Leon_He2014 2013-11-05
  • 打赏
  • 举报
回复
能不能给点原始数据和想要的结果?
唐诗三百首 2013-11-05
  • 打赏
  • 举报
回复

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)
*/

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧