日期:2014-05-17 浏览次数:20530 次
----------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-04-09 17:14:54
-- 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]([NAME] varchar(1),[语文] int,[数学] int,[英语] int)
insert [huang]
select 'A',80,90,75 union all
select 'B',75,80,85
--------------开始查询--------------------------
DECLARE @s NVARCHAR(4000)
SELECT @s = ISNULL(@s + ',', '') + QUOTENAME(Name)
FROM syscolumns
WHERE ID = OBJECT_ID('huang')
AND Name NOT IN ( 'name' )
ORDER BY Colid
EXEC ('select [NAME] ,科目,分数 from huang unpivot ([分数] for [科目] in('+@s+'))b')
----------------结果----------------------------
/*
NAME 科目 分数
---- -------------------------------------------------------- -----------
A 语文 &n