有关数据库的SQL查询问题(100分)

  • 主题发起人 主题发起人 qabo
  • 开始时间 开始时间
Q

qabo

Unregistered / Unconfirmed
GUEST, unregistred user!
我的数据库字段如下
号码 生产1 生产2 生产3 生产4
2006030 100 200 300 400
2006031 200 500 400 800
等等有很多这些数据,现在我想查询从2006030~2006098这段范围内,每间隔3个号码的数据,也就是查询2006030、2006033、2006036、2006039、2006042……
这样的SQL语句怎么写?
 
号码是不是都是连续的,如果都是连续的,就好办了。
首先取第一条纪录的号码,存到一个变量里边
然后根据号码选择每间隔3条的纪录
declare @fristno int
select @fristno=号码 from 表名
select * from 表名 where (号码-@fristno)/3 *3=(号码-@fristno)
 
select * from 表 where 号码 % 3=2 and 号码 between 2006030 and 2006098
 
如果没有间隔,上面两位的方法都很好的。
如果有间隔,可以考虑使用table变量来实现,
declare @tb table (auto_id int IDENTITY (1,1),号码 varchar(10))
insert into @tb select 号码 from 表
select * from 表 where 号码 in (select 号码 from @tb where auto_id % 3=1)
 
都是高手[:D]
 
有点难度,好象用游标可以实现
 
多人接受答案了。
 
后退
顶部