当前位置: 代码迷 >> Sql Server >> sql server查询有关问题
  详细解决方案

sql server查询有关问题

热度:38   发布时间:2016-04-27 17:14:47.0
sql server查询问题
请教高手,我现在想把一个表中如下结构,

student 语文 数学 英语
student1 80 90 85 
student2 85 92 82

在sql 查询输出时变成:


student1 语文 80 
student1 数学 90 
student1 英语 85 
student2 语文 85 
student2 数学 92 
student2 英语 82  


怎么做啊?谢谢!


------解决方案--------------------
SQL code
/*-----------------------------------  Author : htl258(Tony)--  Date   : 2009-09-16 12:01:51--  Version: Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (Intel X86)     Mar 29 2009 10:27:29     Copyright (c) 1988-2008 Microsoft Corporation    Enterprise Evaluation Edition on Windows NT 5.1 <X86> (Build 2600: Service Pack 2)---------------------------------*/--> 生成测试数据表:tbIF NOT OBJECT_ID('[tb]') IS NULL    DROP TABLE [tb]GOCREATE TABLE [tb]([student] NVARCHAR(10),[语文] INT,[数学] INT,[英语] INT)INSERT [tb]SELECT 'student1',80,90,85 UNION ALLSELECT 'student2',85,92,82GO--SELECT * FROM [tb]-->SQL查询如下:SELECT student,课程,分数FROM tb    UNPIVOT(分数 FOR 课程 IN(语文,数学,英语))b /*student    课程    分数student1    语文    80student1    数学    90student1    英语    85student2    语文    85student2    数学    92student2    英语    82*/
------解决方案--------------------
SQL code
IF NOT OBJECT_ID('[tb]') IS NULL    DROP TABLE [tb]GOCREATE TABLE [tb]([student] NVARCHAR(10),[语文] INT,[数学] INT,[英语] INT)INSERT [tb]SELECT 'student1',80,90,85 UNION ALLSELECT 'student2',85,92,82GO--SELECT declare @s nvarchar(4000)select @s=isnull(@s+' union all ','')+'select [student],[课程]='+quotename(Name,N'''')             --isnull(@s+' union all ','') [email protected] all+',[分数]='+quotename(Name)+' from tb'from syscolumns where ID=object_id('tb') and Name not in('student')--排除不转换的列order by Colidprint @sexec(@s+N' order by [student]')/*student    课程    分数student1    语文    80student1    数学    90student1    英语    85student2    英语    82student2    数学    92student2    语文    85*/--select [student],[课程]='语文',[Score]=[语文] from tb union all select [student],[课程]='数学',[Score]=[数学] from tb union all select [student],[课程]='英语',[Score]=[英语] from tb  order by [student]
  相关解决方案