zoukankan      html  css  js  c++  java
  • 宝塔形数据的处理.sql

    /*--

    第一层   -                    1
    第二层   -           2                3
    第三层   -      4        5        6        7
    第四层   -    8   9   10   11   12   13   14  15

    将顺序的数据(1~N)依如下规则排列
    1,排成塔形.
    2,下一层所排数字是对上一层的两倍.(第一层为1个,第二层为2个,第三层4个,如此类推)
    3,自上到下,自左到右紧密排列.

    现在要找出每个号码下面号码的个数.

    --邹建 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,        --那个数下面的子
    @max_level int    --统计到第几层
    )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

    --得到每个号码下面包含的号码个数(作者: DigJim(挖土) )
    create function f_id_num(
    @inputnum int,        --数字
    @totallevel int        --层数
    )returns int
    as
    begin
        declare @i int,@count int,@result float

        --判断这个数所在的层
        select @i=1
            ,@result=@inputnum/2
        
        while @result-1>0
            select @result=@result/2,@i=@i+1
        set @i=@totallevel-@i-1

        --计算这个数包含的个数
        set @count =2
        while @i>0
            select @count=@count*2,@i=@i-1
        return @count-2
    end
    go

    --调用实现查询
    select * from f_id(3,4)

    select dbo.f_id_num(3,4)
    go

    /*--测试结果
    id          num         level       
    ----------- ----------- -----------
    1           3           2
    2           6           3
    3           7           3
    4           12          4
    5           13          4
    6           14          4
    7           15          4

    (所影响的行数为 7 行)
    --*/
  • 相关阅读:
    【springboot】 springboot整合quartz实现定时任务
    Map集合的四种遍历方式
    WCF自引用和循环引用导致的序列化问题
    c#反射
    小助手配置文件列表页
    WPF数据绑定(ItemTemplate和DataTemplate)
    TankMapData
    手机qq协议做的第三方qq软件
    WPF MVVM模式学习
    小助手(应用盒子之我的实现思路及示例程序)
  • 原文地址:https://www.cnblogs.com/shihao/p/2532706.html
Copyright © 2011-2022 走看看