3

这是我的桌子——Select ItemName, ItemDescription from MyTable

我不知道ItemNameItemDescription中的值是什么。

是否可以显示数据,以便将ItemName创建为列,并将ItemDescription作为行值?

4

1 回答 1

1

需要 mssql 2008+

create table mytable( ItemName varchar(10), ItemDescription varchar(10))

insert mytable values('item 1', 'desc1')
insert mytable values('item 2', 'desc2')
insert mytable values('item 1', 'desc2')

declare @list varchar(2000)
;with cte 
as(
select distinct top 100 percent replace(replace(itemname, ']', ''), '[', '') itemname
from mytable
order by itemname
)
select @list = coalesce(@list + ',' + '['+itemname+']', '['+itemname+']') from cte

declare @sql varchar(4000)
set @sql =
'
select * from
(
select replace(replace(itemname, '']'', ''''), ''['', '''') itemname, ItemDescription, row_number() over (partition by ItemName order by ItemDescription) id from mytable
)  a
PIVOT (MAX([ItemDescription]) FOR [itemname] IN ('+@list+')) AS pvt'

exec (@sql)

结果:

id  item 1  item 2
1   desc1   desc2
2   desc2   NULL
于 2013-07-30T09:42:35.350 回答