?? 寶塔形數(shù)據(jù)的處理.sql
字號:
/*--
第一層 - 1
第二層 - 2 3
第三層 - 4 5 6 7
第四層 - 8 9 10 11 12 13 14 15
將順序的數(shù)據(jù)(1~N)依如下規(guī)則排列
1,排成塔形.
2,下一層所排數(shù)字是對上一層的兩倍.(第一層為1個,第二層為2個,第三層4個,如此類推)
3,自上到下,自左到右緊密排列.
現(xiàn)在要找出每個號碼下面號碼的個數(shù).
--鄒建 2004.4--*/
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_id]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_id]
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[f_id_num]') and xtype in (N'FN', N'IF', N'TF'))
drop function [dbo].[f_id_num]
GO
--得到每個號碼下面包含的號碼
create function f_id(
@num int, --那個數(shù)下面的子
@max_level int --統(tǒng)計到第幾層
)returns @re table(id int identity(1,1),num int,level int)
as
begin
declare @level int,@left int,@i int,@j int
select @level=0,@i=@num
while @i>1
select @level=@level+1,@i=@i/2
if @level<@max_level
begin
insert @re values(@num,@level+1)
select @left=(@num%power(2,@level))*2
,@level=@level+1
,@num=power(2,@level)
,@i=0,@j=2
while @level<@max_level
begin
while @i<@j
begin
insert @re values(@left+@num+@i,@level+1)
set @i=@i+1
end
select @level=@level+1
,@left=@left*2
,@num=@num*2
,@i=0,@j=@j*2
end
end
return
end
go
--得到每個號碼下面包含的號碼個數(shù)(作者: DigJim(挖土) )
create function f_id_num(
@inputnum int, --數(shù)字
@totallevel int --層數(shù)
)returns int
as
begin
declare @i int,@count int,@result float
--判斷這個數(shù)所在的層
select @i=1
,@result=@inputnum/2
while @result-1>0
select @result=@result/2,@i=@i+1
set @i=@totallevel-@i-1
--計算這個數(shù)包含的個數(shù)
set @count =2
while @i>0
select @count=@count*2,@i=@i-1
return @count-2
end
go
--調(diào)用實現(xiàn)查詢
select * from f_id(3,4)
select dbo.f_id_num(3,4)
go
/*--測試結(jié)果
id num level
----------- ----------- -----------
1 3 2
2 6 3
3 7 3
4 12 4
5 13 4
6 14 4
7 15 4
(所影響的行數(shù)為 7 行)
--*/
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -