Sql Server 2列数据转换为 2行 (行转列列转行)



create table temp1
(
count_ int,
memo nvarchar(40)
)
go


insert into temp1
values (1,'AM')
insert into temp1
values (2,'SS')


go




DECLARE @col VARCHAR(MAX)
select @col=ISNULL(@col+'],[','')+QUOTENAME(LTRIM(memo)) from temp1  
set @col = replace(@col,']],[[','],[')
print @col
declare @sql nvarchar(max)
set  @sql = 'select r.*  from 
(select count_,memo from  temp1 lf
)
as t
pivot
(
sum(t.count_)
for t.memo in ('+@col+')
)
as r'
exec sp_executesql @sql


drop table temp1


--感谢Crazyba支持.

你可能感兴趣的:(Sql Server 2列数据转换为 2行 (行转列列转行))