日期:2014-05-17  浏览次数:20952 次

请教一条MS-SQL语句的查询方法,比较急,必解贴,请大家多帮帮忙看看
我的数据库表值如下:
id                           sz
1                               4
2                               5
3                               8
4                               1
5                               4
6                               5
7                               0
8                               7
9                               3
我想,比如我在一个页面输入4和5,就找出在数据库中,有多少条记录是4和5连着的形式,或找出所以4和5连着的下一条记录,像id是1,id是2就是4,5连着的情况,找出下条记录(是8),还有id是5和id是6的情况也找出来
不知说的明白不?请大家多费心了


------解决方案--------------------
有多少条记录是4和5连着的形式
//////////////////////////////////
id=1和id=2是4和5连着的形式,那这算一条记录还是算两条记录?
------解决方案--------------------
应该不难,你到sql 专区问会更快得到答案!
------解决方案--------------------
抛砖引玉阿,用什么语法你自己改。
如下:
-------------------------------------
定义数据库链接部分从略了
sql= "select * from 表格名 "
dim kk '结果集
kk= " "
rs.open
while not rs.eof
if rs( "sz ")=4 then
rs.movenext
if rs( "sz ")=5 then
rs.movenext
'45相连则取sz,结果之间用符号隔开。
kk=kk & rs( "sz ") & "; "
rs.movenext
end if
else
rs.movenext
end if
wend
'循环完毕,得结果集kk
'可以拆成数字
shuzu=split(kk, "; ")
mount=ubound(shuzu)-1 '有多少结果,最后一个为空要去掉。
------解决方案--------------------
如果ID是连接的,那有办法。
下面这个语句是求出所有连续4,5的下一条记录的ID。
select t1.id+1 as tNextID
from tblname as t1 inner join(
select id+1 as Nextid,sz+1 as Nextsz
from tblname
where sz=4) as t2 on t1.id=t2.id and t1.sz=t2.nextsz

如果ID是不连续的,那就不好办了。



------解决方案--------------------
declare @t table(d1 int, sz int)
insert into @t
select 2, 4
union all select 3, 5
union all select 4, 8
union all select 5, 1
union all select 6, 4
union all select 7, 5
union all select 8, 0
union all select 9, 4
union all select 10, 5
union all select 11, 7
union all select 12, 3

drop table #tmp

create table #tmp(
s int identity,
d1 int not null,
x int not null
)

insert into #tmp(d1, x) select d1, sz from @t order by d1 asc

declare @m int, @n int, @h int
set @m = (select max(s) from #tmp) --从最大ID开始
set @n = 0 --上一个ID
set @h = 0 --计数

while @m > 0
begin
if (select x from #tmp where s = @m and abs(x - (select x from #tmp where s = @n and (x = 4 or x = 5))) = 1 an