sql多列合并为一列多行
如表tab有列id,a,b,c1a1b1c12a2b2c2查询有显示的是ids1a1b1c12a2b2c2...
如 表tab 有列id, a, b, c
1 a1 b1 c1
2 a2 b2 c2
查询有显示的是
id s
1 a1
b1
c1
2 a2
b2
c2 展开
1 a1 b1 c1
2 a2 b2 c2
查询有显示的是
id s
1 a1
b1
c1
2 a2
b2
c2 展开
2个回答
展开全部
SQL SERVER2005以上版本可以
use Tempdb
go
--> -->
if not object_id(N'Tempdb..#') is null
drop table #
Go
Create table #([a] int,[b] nvarchar(2),[c] nvarchar(2),[d] nvarchar(2))
Insert #
select 1,N'a1',N'b1',N'c1' union all
select 2,N'a2',N'b2',N'c2'
Go
Select a=case when ColName='b' then rtrim(a) else '' end,s
from # AS a
UNPIVOT (s FOR ColName IN([b],[c],[d]))AS b
/*
a s
1 a1
b1
c1
2 a2
b2
c2
*/
use Tempdb
go
--> -->
if not object_id(N'Tempdb..#') is null
drop table #
Go
Create table #([a] int,[b] nvarchar(2),[c] nvarchar(2),[d] nvarchar(2))
Insert #
select 1,N'a1',N'b1',N'c1' union all
select 2,N'a2',N'b2',N'c2'
Go
Select a=case when ColName='b' then rtrim(a) else '' end,s
from # AS a
UNPIVOT (s FOR ColName IN([b],[c],[d]))AS b
/*
a s
1 a1
b1
c1
2 a2
b2
c2
*/
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询