表(a b c 是字段名)
a b c
1 1 1
结果集
a 1
b 1
c 1
要怎么把表行改列,列改行?
------解决方案--------------------
select a union all
select b union all
select c
?
------解决方案--------------------
動態?
declare @s nvarchar(4000)
select @s=isnull(@s+' union all ','')+' select '+quotename(Name,'''')+', '+quotename(Name,'''')
+'='+quotename(Name) +' from tb '
from syscolumns where ID=object_id('tb')
exec (@s)
------解决方案--------------------
写个静态的:
if object_id('tb') is not null
drop table tb
go
create table tb(a int,b int,c int)
insert tb
values(1,1,1)
select 'a' as name,a from tb
union all
select 'b' as name,b from tb
union all
select 'c' as name,c from tb
/*
name a
a 1
b 1
c 1
*/
------解决方案--------------------
unpivot的方法:
if object_id('tb') is not null
drop table tb
go
create table tb(a int,b int,c int)
insert tb
values(1,1,1)
select e,n
from tb
unpivot
(
n for e in (a,b,c)
)t
select e,n
from tb
unpivot
(
n for e in (a,b,c)
)t
/*
e n
a 1
b 1
c 1
*/
------解决方案--------------------
create table 表
(a int,b int,c int)
insert into 表(a,b,c)
select 1,1,1
select col,val
from 表 a
unpivot(val for col in(a,b,c)) p
/*
col val
------------- -------------
a 1
b 1
c 1
(3 row(s) affected)
*/
------解决方案--------------------
沒列名? 是這個?
create table #tb (a int,b int,c int)
insert into #tb
select 1,1,1
declare @s nvarchar(4000)
select @s=isnull(@s+' union all ','')+' select '+quotename(Name,'''')+' as 列名, '+quotename(Name,'''')
+'='+quotename(Name) +' from #tb '
from tempdb .sys. syscolumns where ID=object_id(N'tempdb.dbo.#tb')
exec (@s)
drop table #tb
------解决方案--------------------
要动态的撒!
这样吗:
drop table tb
create table tb (a int,b int,c int)
insert into tb
select 1,1,1
declare @s nvarchar(4000)
set @s = '';
select @s= @s + ',['+name+']'
from sys.columns
where object_id = object_id('tb')
set @s = 'select col_name,col_value from tb unpivot(col_value for col_name in (' +
stuff(@s,1,1,'') +'))t'
--select @s