这是我的表 - Select ItemName, ItemDescription from MyTable
我不知道 ItemName 或 ItemDescription 中的值是什么。
是否可以显示数据,以便将 ItemName 创建为列, ItemDescription 是行值?
答案 0 :(得分: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