首先看看效果是不是想要的
变成
ok,我的效果达到了。那就记录下代码吧。
create table temp1
(
count_ int,
memo nvarchar(40)
)
go
insert into temp1
values (1,'AM')
insert into temp1
values (2,'SS')
go
select *from temp1
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
)
as t
pivot
(
sum(t.count_)
for t.memo in ('+@col+')
)
as r'
print @sql
exec sp_executesql @sql