declare @i int,@Str varchar(3000)
set @Str=''
set @i=0
while @i<=49 
 begin
   @Str=@str+' select max(c1),min(c1),avg(c1) from t where datepart(yy,sj)=2004
  union all '
  set @i=@i+1
 end
  set @str=@str+'select max(c1),min(c1),avg(c1) from t where datepart(yy,sj)=2004'
  exec(@Str)
go

解决方案 »

  1.   

    create table #t(
    a int,
    b int,
    c int)insert into #t select 1,3,2
    insert into #t select 2,2,3
    insert into #t select 3,1,1select min(a),max(a),avg(a),min(b),max(b),avg(b),min(c),max(c),avg(c) from #tdrop table #t
      

  2.   

    declare @i int,@Str varchar(3000)
    set @Str=''
    set @i=1
    while @i<=49 
     begin
       @Str=@str+' select max(c1),min(c1),avg(c1) from t where datepart(yy,sj)=2004
      union all '
      set @i=@i+1
     end
      set @str=@str+' select max(c1),min(c1),avg(c1) from t where datepart(yy,sj)=2004'
      exec(@Str)
    go
      

  3.   

    不想写就用动态语句,实质也是写出那个union 语句
      

  4.   


    declare @i varchar(10),@s varchar(8000)
    select @i=0,@s=''
    set rowcount 50
    select @i=@i+1,@s=@s+' union all select max(c'+@i+'),min(c'+@i+'),avg(c'+@i+') from t where datepart(yy,sj)=2004'
    from syscolumns 
    set @s=stuff(@s,1,11,'')
    set rowcount 0
    exec(@s)
      

  5.   

    declare @i int,@s varchar(8000)
    select @i=1,@s=''
    while @i<=49
    begin
    select @s=@s+' select max(c'+cast(@i as varchar)+'),min(c'+cast(@i as varchar)+'),avg(c'+cast(@i as varchar)+') from t where datepart(yy,sj)=2004 union all '
    from syscolumns 
    set @i=@i+1
    end
    set @s=@s+' select max(c50),min(c50),avg(c50) from t where datepart(yy,sj)=2004'
    exec(@s)
      

  6.   

    declare @i varchar(10),@s varchar(8000)
    select @i=0,@s=''
    set rowcount 50
    select @i=@i+1,@s=@s+' union all select max(c'+@i+'),min(c'+@i+'),avg(c'+@i+') from t where datepart(yy,sj)=2004'
    from syscolumns 
    set @s=stuff(@s,1,11,'')
    set rowcount 0
    exec(@s)