这样的SQL怎么实现?(50分)

1先建立一个临时表
create table #temp(开奖期数 varchar(10) not null,
号码1 varchar(2),--实际是甚幺类型就是甚幺类型
号码2 varchar(2),
号码3 varchar(2),
号码4 varchar(2),
号码5 varchar(2),
号码6 varchar(2),
号码7 varchar(2)--假设最多有7个号码, 有几个号码就建立几个字段
)

2.用指针遍历
declare @id varchar(10)
declare @num varchar(2)
declare @num1 varchar(2)
declare @num2 varchar(2)
declare @num3 varchar(2)
declare @num4 varchar(2)
declare @num5 varchar(2)
declare @num6 varchar(2)
declare @num7 varchar(7)
declare cursor_type cursor for
select 开奖期数,号码 from 彩票表
open cursor_type
fetch next from cursor_type into @id,@num
while @@fetch_status=0
begin
if exists(select 开奖期数 from #temp where 开奖期数=@id )
begin
select @num1=isnull(号码1,''),@num2=isnull(号码2,''),@num3=isnull(号码3,''),@num4=isnull(号码4,''),@num5=isnull(号码5,''),@num6=isnull(号码6,''),@num7=isnull(号码7,'') from #temp where 开奖期数=@id
if @num2=''
update #temp set 号码2=@num where 开奖期数=@id
else if @num3=''
update #temp set 号码3=@num where 开奖期数=@id
else if @num4=''
update #temp set 号码4=@num where 开奖期数=@id
else if @num5=''
update #temp set 号码5=@num where 开奖期数=@id
else if @num6=''
update #temp set 号码6=@num where 开奖期数=@id
else if @num7='' --假设最多有7个号码
update #temp set 号码7=@num where 开奖期数=@id
end
else
insert into #temp(开奖期数, 号码1) values(@id, @num)
fetch next from cursor_type into @id,@num
end
close cursor_type
deallocate cursor_type
select * from #temp--输出结果集
drop table #temp--释放临时表

--不管有多少期,上面的代码都能满足,如果没有7个号码,就把代码中带7的代码删掉即可
例如只有5个号码,那么把’号码6 varchar(2),号码7 varchar(2)’,’ declare @num6 varchar(2)
declare @num7 varchar(7)’,’ @num6=isnull(号码6,''),@num7=isnull(号码7,'')’,’ else if @num6=''
update #temp set 号码6=@num where 开奖期数=@id else if @num7=''码 update #temp set 号码7=@num where 开奖期数=@id’删除即可


 
select 号码, count(号码) as 頻率 from 彩票表 group by 号码
 
WANGSHENGYUN给了我很大的启示,游标这东西是个好东西,解决了我第一个提出的问题,但是我现在倒更想解决第二个问题,出于主题不够清晰,在这先结掉这一贴,重新开贴希望大侠们继续帮忙。
 
但,我感觉用交叉表也可以解决啊,不用游标
 

Similar threads

D
回复
0
查看
2K
DelphiTeacher的专栏
D
D
回复
0
查看
1K
DelphiTeacher的专栏
D
D
回复
0
查看
867
DelphiTeacher的专栏
D
D
回复
0
查看
1K
DelphiTeacher的专栏
D
S
回复
0
查看
950
SUNSTONE的Delphi笔记
S
顶部