求教一句sql查询语句

lqsmn613 2012-07-02 04:07:06
具体情况是在一张表内有两个字段,假设为 :num1 num2
分别表示开始数字与结束数字,例如有数据为:
1 10
11 20
21 30
31 40
41 50
以上5条数据;

现在我这里给予的查询条件是一个区间,比如是13-35
查询到的数据应该是后面四条,请问,这种情况如何查询比较好?
...全文
97 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
lqsmn613 2012-07-02
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]

SQL code
--> 测试数据:[tb]
IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb]
GO
CREATE TABLE [tb]([num1] INT,[num2] INT)
INSERT [tb]
SELECT 1,10 UNION ALL
SELECT 11,20 UNION ALL
SELECT 21,30 UNION ALL
S……
[/Quote]
好吧,谢啦,我自己想太多了!
  • 打赏
  • 举报
回复

--> 测试数据:[test]
if object_id('[test]') is not null
drop table [test]
create table [test]([id] int,[value] int)
insert [test]
select 1,10 union all
select 11,20 union all
select 21,30 union all
select 31,40 union all
select 41,50
declare @str varchar(1000)
set @str='13-35'
select @str=REPLACE(@str,'-',' and ')
exec('select * from test where [value] between '+@str+' or id between '+@str)
/*
id value
11 20
21 30
31 40
*/


  • 打赏
  • 举报
回复

--> 测试数据:[test]
if object_id('[test]') is not null
drop table [test]
create table [test]([id] int,[value] int)
insert [test]
select 1,10 union all
select 11,20 union all
select 21,30 union all
select 31,40 union all
select 41,50
declare @str varchar(1000)
set @str='13-35'
select @str=REPLACE(@str,'-',' and ')
exec('select * from test where [value] between '+@str)
/*
id value
----------------
11 20
21 30
*/



不知道你的结果是怎么出来的
lqsmn613 2012-07-02
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

为什么是最后四条呢?
[/Quote]
因为给的条件是13到35啊。
NND,看错了,是中间三条才对。。。呵呵
筱筱澄 2012-07-02
  • 打赏
  • 举报
回复
--> 测试数据:[tb]
IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb]
GO
CREATE TABLE [tb]([num1] INT,[num2] INT)
INSERT [tb]
SELECT 1,10 UNION ALL
SELECT 11,20 UNION ALL
SELECT 21,30 UNION ALL
SELECT 31,40 UNION ALL
SELECT 41,50 UNION ALL
SELECT 20,10 --增加一个[num2]>[num1]的
--------------开始查询--------------------------
--13-35
--应该是下面三行才合理吧
SELECT * FROM [tb] WHERE [num2]>13 AND [num2]>[num1] AND [num1]<35
----------------结果----------------------------
/*
num1 num2
----------- -----------
11 20
21 30
31 40

(3 行受影响)

*/
筱筱澄 2012-07-02
  • 打赏
  • 举报
回复
为什么是最后四条呢?

34,838

社区成员

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

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