日期:2014-05-17 浏览次数:20448 次
declare @sql nvarchar(max)
select @sql=ISNULL(@sql,'')+ ',MAX(case when 种类='''+rtrim(种类)+''' then '+name+' else null end)['+rtrim(种类)+name+']'
from (select b.name
from sysobjects a,syscolumns b
where a.name = 'tb' and a.id= b.id and b.name!='种类'
)t,tb order by 种类,name
set @sql='select '+stuff(@sql,1,1,'')+' from tb'
exec (@sql)
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-02-25 17:00:36
-- Version:
-- Microsoft SQL Server 2008 R2 (SP1) - 10.50.2500.0 (X64)
-- Jun 17 2011 00:54:03
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1, v.721)
--
----------------------------
--> 测试数据:[huang]
if object_id('[huang]') is not null drop table [huang]
go
create table [huang]([种类] varchar(6),[厂家] varchar(1),[价格] int,[规格型号] varchar(2))
insert [huang]
select '铅笔','A',10,'2B' union all
select '钢笔','B',20,'HB' union all
select '圆珠笔','C',15,'SB'
--------------开始查询--------------------------
DECLARE @s NVARCHAR(4000)
SET @s = ''
SELECT @s = @s + ',' + 种类+'厂家' + '=max(case when [种类]='
+ QUOTENAME([种类], '''') + ' then [厂家] else ''0'' end)'+ ',' + 种类+'价格' + '=max(case when [种类]='
+ QUOTENAME([种类], '''') + ' then [价格] else ''0'' end)'+ ',' + 种类+'规格型号' + '=max(case when [种类]='
+ QUOTENAME([种类], '''') + ' then [规格型号] else ''0'' end)'
FROM [huang]
GROUP BY 种类
SELECT @s=SUBSTRING (@s,2,LEN(@s))
EXEC ('select '+@s+' from [huang] '