日期:2014-05-18  浏览次数:20506 次

排列3 SQL算法求解
期数 第1位 第2位 第3位
---------------------- ---------------------- ---------------------- ----------------------
4010 2 7 4
4011 3 6 4
4012 3 0 5
4013 0 3 2
4014 3 5 9
4015 5 9 8
4016 4 4 5
4017 1 9 3
4018 1 2 9
4019 7 1 1
4020 1 0 9
4021 3 9 3
............................

这个排列3的数据...

假如 我这边需要从期数4015开始,查找最开始的期数到期数4015这个期间,出现次数最多的两个数字和次数最小的数字

找出两个值以后,再从下一个期数4016开始,方法和上面类似....

这样把每期输出的出现的次数最多的数字和最少的数字,存在另一张表中。
希望高手用快捷的办法..优化、。。

------解决方案--------------------
定义一张表,记录10行记录。
次数表
数字 第一位出现次数,第二位出现次数,第三位出现次数
1
2
3
4
5
6
7
8
9

4015之前 select 第一位,count(*) into #tmp from 表 where 期数<4015
group by 第一位

update 次数表 set 第一位出现次数=count
from 次数表 c, #tmp t
where c.数字=t.第一位

drop table #tmp
select 第二位,count(*) into #tmp from 表 where 期数<4015
group by 第二位

update 次数表 set 第二位出现次数=count
from 次数表 c, #tmp t
where c.数字=t.第二位
drop table #tmp
select 第三位,count(*) into #tmp from 表 where 期数<4015
group by 第三位

update 次数表 set 第三位出现次数=count
from 次数表 c, #tmp t
where c.数字=t.第三位
drop table #tmp

求数字下面语句

select max(第一位),min(第一位) into #tmp2
from 次数表

select max(第一位) 第二位
from 次数表 where 第一位 not in (select 第一位 from #tmp2)

4015之后的就使用游标
开始累加 次数表







------解决方案--------------------
create table record
(
period int,
firstnum int,
secondnum int,
third int
)

insert into record
select 4011,2,3,4
union all
select 4012,2,6,7
union all
select 4013,8,3,5
union all
select 4014,7,4,7
union all
select 4015,1,6,5
union all
select 4016,0,4,1
union all
select 4017,4,3,2
union all
select 4018,4,7,3
union all
select 4019,7,8,9

create table totaltable
(
toperiod int,
top1 int,
top2 int,
lastone int
)

create proc test
(
@periodnum int
)
as

create table #temp
(
num int
)
 
insert into #temp
select firstnum as num from record where period<@periodnum
union all
select secondnum as num from record where period<@periodnum
union all
select third as num from record where period<@periodnum


declare @minNum int,
@maxNum int,
@secMaxNum int

--出现次数最少的
select @minNum=num from 
(select top 1 num,COUNT(*) as numcount from #temp group by num order by numcount) a
--出现次数最多的
select @maxNum=num from
(select top 1 num,COUNT(*) as numcount from #temp group by num order by numcount desc ) b
--出现次数次数第2多的
select @secMaxNum=num from
(
select top 1 * From 
(select top 2 num,COUNT(*) as numcount from #temp group by num order by numcount desc) e order by numcount ) c

insert in