首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

行转列的有关问题,HELP

2013-04-21 
行转列的问题,HELP!如:NAME语文数学英语A809075B758085现想换成 NAME科目分数 A语文80A数学90A英语75B语文

行转列的问题,HELP!
如:
NAME  语文   数学   英语
A      80    90    75
B      75     80    85

现想换成 
NAME  科目   分数 
A     语文    80
A     数学    90
A     英语    75
B     语文    75
B     数学    80
B     英语    85


[解决办法]

----------------------------
-- 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    语文                                                                                                                               80


A    数学                                                                                                                               90
A    英语                                                                                                                               75
B    语文                                                                                                                               75
B    数学                                                                                                                               80
B    英语                                                                                                                               85
*/

热点排行