日期:2014-05-17  浏览次数:20441 次

求教,如何将多列数据平铺进一行
表:

列名  no  a   b   c
      1   a1  b1  c1
      2   a2  b2  c2
      3   a3  b3  c3
      ...

输出格式为:

列名:   
输出内容:  a1  b1  c1  a2  b2  c2   a3  b3  c3 ...

先谢谢各位高手了!

------解决方案--------------------

declare @v nvarchar(500)
select @v=''
select @v=@v+' '+a+' '+b+' '+c from tab
select @v

------解决方案--------------------
select a+' '+b+' '+c+' ' from tab for xml path('')

------解决方案--------------------
select ' '+a+' '+b+' '+c from 表 for xml path('')
------解决方案--------------------

create table zy
(no int, a varchar(5), b varchar(5), c varchar(5))

insert into zy
select 1, 'a1', 'b1', 'c1' union all
select 2, 'a2', 'b2', 'c2' union all
select 3, 'a3', 'b3', 'c3'


select * from zy

/*
no          a     b     c
----------- ----- ----- -----
1           a1    b1    c1
2           a2    b2    c2
3           a3    b3    c3

(3 row(s) affected)
*/


declare @tsql varchar(6000)

select @tsql='select '

select @tsql=@tsql+' max(da'+rtrim(no)+') da'+rtrim(no)+','
                  +' max(db'+rtrim(no)+') db'+rtrim(no)+','
                  +' max(dc'+rtrim(no)+') dc'+rtrim(no)+','
 from (select distinct no from zy) z

select @tsql=left(@tsql,len(@tsql)-1)+' from (select no,'

select @tsql=@tsql+' max(case when no='+rtrim(no)+' then a else '''' end) da'+rtrim(no)+','
                  +' max(case when no='+rtrim(no)+' then b else '''' end) db'+rtrim(no)+','
                  +' max(case when no='+rtrim(no)+' then c else '''' end) dc'+rtrim(no)+','
 from (select distinct no from zy) z

select @tsql=left(@tsql,len(@tsql)-1)+' from zy group by no) t'