sql2000 求最大连续和间隔新手,没说清楚请谅解,谢谢
谢谢
问题1
表1中,,每个数据列里就有1个数据,数据1到数据10列里是10个数字 排列id1接id2,就是把全部的数据当成1条数据,求每个数的最大连续和最大间隔
id 数据1数据2.。。数据10
1 1 2 1 2 3 4 12 17 17
2 17 2 3 4 4 4 4 5 10
3.。。等于就是按如下排列统计。id1 数据1.。。数据10 + id2 数据1.。。数据10
1 2 1 2 3 4 12 17 17 17 2 3 4 4 4 4 5 10得表2
每个数字 最大连续次数 最大间隔次数  
1 0 1
2 2 7
3 0 7
4 4 6
.。。
17 3 8

解决方案 »

  1.   

    一句话,这种逻辑放到前台程序处理吧,比sql快
      

  2.   

    create table tb(id int,数据1 int,数据2 int,数据3 int,数据4 int,数据5 int,数据6 int,数据7 int,数据8 int,数据9 int,数据10 int)insert tb 
    select 1 ,1 ,2 ,1 ,2 ,3 ,4 ,12 ,17 ,17,1 union all
    select 2 ,17 ,2 ,3 ,4 ,4 ,4 ,4 ,5 ,10,1 union all
    select 3 ,1 ,5 ,6 ,5 ,4 ,4 ,6 ,8 ,10,1 
    select identity(int,1,1) as id1,id,data into #temp1
    from 
    (select id,数据1 as data from tb
    union all 
    select id,数据2 from tb
    union all 
    select id,数据3 from tb
    union all 
    select id,数据4 from tb
    union all 
    select id,数据5 from tb
    union all 
    select id,数据6 from tb
    union all 
    select id,数据7 from tb
    union all 
    select id,数据8 from tb
    union all 
    select id,数据9 from tb
    union all 
    select id,数据10 from tb) aselect identity(int,1,1) as id2,data  into #temp2  from #temp1 order by id,id1 
    select a.data,isnull(b.maxlx,0)最大连续次数,isnull(c.maxjc,0)最大间隔次数
    from
    (select distinct data from #temp2) a
    left join
    (
    --最大连续次数
    select a.data,max(b.id2-a.id2) as maxlx from #temp2 a,#temp2 b
    where a.data=b.data and  a.id2<b.id2
    and not exists
    (select 1 from #temp2 c where c.data<>a.data and c.id2>a.id2 and c.id2<b.id2)
    group by a.data
    ) b on a.data=b.data
    left join
    (
    --最大间隔次数
    select a.data,max(b.id2-a.id2)-1 as maxjc from #temp2 a,#temp2 b
    where a.data=b.data and  a.id2<b.id2
    and  exists
    (select 1 from #temp2 c where c.data<>a.data and c.id2>a.id2 and c.id2<b.id2)
    and not exists
    (select 1 from #temp2 c where c.data=a.data and c.id2>a.id2 and c.id2<b.id2)
    group by a.data
    ) c on a.data=c.datadrop table tb,#temp1,#temp2
    /*
    data        最大连续次数      最大间隔次数      
    ----------- ----------- ----------- 
    1           1           9
    2           0           7
    3           0           7
    4           3           7
    5           0           3
    6           0           3
    8           0           0
    10          0           9
    12          0           0
    17          1           1
    */