如下表:
         key1     key2    time 
           1          01       t1
           2          01       t2
           3          02       t21
           4          02       t22想查詢後得到下面結果 :
 
        key1     key2    time      子序號
           1          01       t1          1
           2          01       t2          2
           3          02       t21        1
           4          02       t22        2在結果中加入子序號 , 向各位請教 !!!

解决方案 »

  1.   

    你添加子序号的规律是什么啊?可以用case来区分各种情况,然后确定子序号。比如 select ...(省略) , case key2 when ''01'' then ''1'' else ''02'' then ''2'' end as 子序號 from ...你可以写类似的,不知是否能满足你的要求
      

  2.   

    如果是很多的话,这种东西的实现不是SQL可以做的了,如果在程序中要实现的话,那么你要做的就是在显示的时候有记数,如果只是2个的重复的话,那么就用上面那位的方法就可以了。
      

  3.   

    create table #t1(key1 int,key2 char(2),time char(4))insert into #t1 values(1,'01','t1')
    insert into #t1 values(2,'01','t2')
    insert into #t1 values(3,'02','t21')
    insert into #t1 values(4,'02','t22')select * from #t1
    /*结果
    1 01 t1  
    2 01 t2  
    3 02 t21 
    4 02 t22 
    */select key1,key2,time,子序號=(select count(key2) from #t1 where key1<=a.key1 and key2='01') from #t1 a where a.key2='01' 
    union
    select key1,key2,time,子序號=(select count(key2) from #t1 where key1<=b.key1 and key2='02') from #t1 b where b.key2='02' order by key1
    /*结果
    1 01 t1   1
    2 01 t2   2
    3 02 t21  1
    4 02 t22  2
    */drop table #t1
      

  4.   

    如果你的key2的值有多个,用多个union
      

  5.   


    select key1,key2 ,time,
           [子序號]=(select count(1) from 表 where time=a.time and key1<=a.key1)
    from 表 as a