数据库中的数据,取出来后如  
a1  a2  a3  a4  
b1  b2  b3  b5  
c1  c2  c3  c4  
需要在报表里显示为  
a1  b1  c1  
a2  b2  c2  
a3  b3  c3  
a4  b4  c4  
 
这个该怎么处理?或者提供个存储过程  
我现在是用程序把它转到临时表里

解决方案 »

  1.   

    --创建测试表
    create table t(id int identity(1,1),a int ,b int, c int)
    go
    --插入测试数据
    insert into t select 1,2,3
    union select 2,3,4
    union select 3,4,5
    union select 4,5,6
    union select 5,6,7
    union select 6,7,8
    go
    --创建存储过程
    create proc p_t(@sFieldList varchar(2000))
    as
    begin
    declare @s1 varchar(8000)
    declare @s2 varchar(8000)
    declare @s3 varchar(8000)
    declare @s4 varchar(8000)
    declare @s5 varchar(8000)
    declare @s6 varchar(8000)
    declare @s7 varchar(8000)
    set @s1='select x '
    select @s1=@s1+',min(['+convert(varchar(20),id)+'])['+convert(varchar(20),id)+']'
    from (select distinct id from t) z order by id
    set @s1=@s1+char(13)+' from ('set @s4=''
    select @s4=@s4+',min(['+convert(varchar(20),id)+'])['+convert(varchar(20),id)+']'
    from (select distinct id from t) z order by id
    set @s4='select '+substring(@s4,2,len(@s4))
    set @s5=@s4+' into #tt from ( '+char(13)
    set @s4=@s4+' from ('+char(13)
    set @s2=' case '
    select @s2=@s2+' when x='''+name+''' then ['+name+']'+char(13)
    from (select name from syscolumns where id =(select id from sysobjects where name='t') and charindex(name,@sFieldList)>0) z
    set @s2=@s2+' end '+char(13)
    set @s3 = 'select x '
    select @s3=@s3+' ,case id when '+convert(varchar(20),id)+ ' then '+@s2+' end['+convert(varchar(20),id)+']'+char(13)
    from (select distinct id from t) z order by id
    set @s7=''
    set @s6=' select id,'
    select @s6=@s6+' case when id ='+convert(varchar(20),id)+' then ['+convert(varchar(20),id)+'] else ',
    @s7=@s7+' end '
    from (select distinct id from t) z order by id
    exec(@s5+@s1+@s3+'from (select name as x from syscolumns where id =(select id from sysobjects where name=''t'') and charindex(name,'''+@sFieldList+''')>0 ) t1, t) z group by x )z1 select * from #tt')end
    go
    select * from t
    --调用
    exec p_t 'a,b,c'--动态的字段名
    go
    --删除表
    drop table t
    drop proc p_t
    go
    /*原始记录
    id a b c
    ----------- ----------- ----------- -----------
    1 6 7 8
    2 1 2 3
    3 2 3 4
    4 3 4 5
    5 4 5 6
    6 5 6 7
    */
    /*中间结果
    x 1 2 3 4 5 6
    ---- ----------- ----------- ----------- ----------- -----------
    a 6 1 2 3 4 5
    b 7 2 3 4 5 6
    c 8 3 4 5 6 7
    */