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

【求教 生成一定规律的数字表】
本帖最后由 feixianxxx 于 2010-07-21 21:48:39 编辑 问题:
我想生成这么一个表:
create table tb (col1 int,col2 int,col3 int )

这三个字段的规律是这样的:

col1 col2 col3 三个字段 
1.每个字段的数值范围是 1-9 
2.对于每一行 三个字段在不可以出现重复值 举例:1 1 3 这样的不允许
3.行与行之间不可以相同  ,就是行要唯一

生成的样式就是如下:
col1 col2 col3 
1     2    3
4     2    3 
....
3     2    1
9     8    2

.....
注意红色部分 这样的记录也允许 

我算了下 一共有9*8*7=504行


这个我说的应该清楚了吧。。。。

我写了个很慢的死的代码,郁闷死,N分钟后 还是没算出来全部的。。。


--计算数值表
create table tmp (col1 int,col2 int,co3 int)
go

declare @n int ,@col1 int,@col2 int,@col3 int 
set @n=0
while (@n<=504)
begin
select @col1=max(case when rn=1 then number end) ,@col2=max(case when rn=2 then number end) ,@col3=max(case when rn=3 then number end) 
from (
select number,rn=row_number() over(order by getdate())
from (
select top 3 number 
from  master..spt_values 
where type='p' and number between 1 and 9 order by checksum(newid())
)k
) z
select  @col1,@col2,@col3 
if(not exists(select * from tmp where col1=@col1 and col2 = @col2 and co3 =@col3))
begin
set @n = @n+1;
insert tmp select @col1,@col2,@col3;
end
end 
go
select * from tmp 
drop table tmp 


------最佳解决方案--------------------

select *
from
(
select left(rtrim(number),1) as col1, substring(rtrim(number),2,1) as col2,right(rtrim(number),1) as col3
from master..spt_values
where type='p'
and number between 123 and 987
) X
where convert(int,col1)*convert(int,col2)*convert(int,col3)>0
and col1<>col2
and col1<>col3
and col2<>col3

------其他解决方案--------------------
[code=SQL]
declare @test table(n int)
insert @test
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 5 union all
select 6 union all
select 7 union all
select 8 union all 
select 9 

SELECT A.N,B.N,C.N FROM @test A,@test B,@test C WHERE A.N<>B.N AND B.N<>C.N AND A.N<>C.N

------其他解决方案--------------------
sssssssss
------其他解决方案--------------------
1111
------其他解决方案--------------------
2222222