表中列styleid (styleid=1,2,3,4,5)
想将表按styleid得styleid=1,styleid=2.....的每类的前5条记录提出来,应该怎样写一条select??

解决方案 »

  1.   

    create table a(styleid int)
    insert into a
    select 1
    union all
    select 1
    union all
    select 1
    union all
    select 1
    union all
    select 1
    union all
    select 1
    union all
    select 2
    union all
    select 2
    union all
    select 2
    union all
    select 2
    union all
    select 2
    union all
    select 
    2
    union all
    select 3
    union all
    select 3
    union all
    select 3declare @i int
    declare @sql varchar(8000)
    set @i=1
    select @sql='select top 5 * from a where '
    while @i<4
    begin
     select @i=@i+1
     select @sql=@sql+'styleid='+cast(@i as varchar(10))+' union all ' +@sql
     
    end
     select @sql=@sql+'styleid='+cast(@i as varchar(10))
     exec(@sql)
      

  2.   


      declare @s_back varchar(300),@s_num int
      set @s_back='',@s_num=1
      while @s_num<5
       begin
        @s_back=@s_back+' select top 5 * from tb where styleid='+cast(@s_num as varchar(10))
        set @s_num=@s_num+1
    @s_back=@s_back+'union all'
       end
       exec(@s_back)
      

  3.   

    除了用union语句就是写存储过程返回结果集了