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

请问动态PIVOT查询结果列排序有关问题

2012-10-15 
请教动态PIVOT查询结果列排序问题if not object_id(Class) is nulldrop table ClassGoCreate table Clas

请教动态PIVOT查询结果列排序问题
if not object_id('Class') is null
  drop table Class
Go
Create table Class([Student] nvarchar(2),[Course] nvarchar(2),[Score] INT,id int)
Insert Class
select N'张三',N'语文',78,1 union all
select N'张三',N'数学',87,2 union all
select N'张三',N'英语',82,3 union all
select N'张三',N'物理',90,4 union all
select N'李四',N'语文',65,1 union all
select N'李四',N'数学',77,2 union all
select N'李四',N'英语',65,3 union all
select N'李四',N'物理',85,4 
GO

--运行行列转换语句

declare @s nvarchar(4000)
Select @s=isnull(@s+',','')+quotename([Course]) from Class group by[Course] --isnull(@s+',','') 去掉字符串@s中第一个逗号
exec(
'select [Student],'
  +@s+
'from
  (select student,course,score from Class ) a 
 pivot
  (
  max([Score]) 
 for 
  [Course]
  in('+@s+')
  )b '
  )
--得到结果:
Student 数学 物理 英语 语文
------- ----------- ----------- ----------- -----------
李四 77 85 65 65
张三 87 90 82 78

(2 行受影响)


--希望得到的结果,列按ID进行排序:
Student 语文 数学 英语 物理
------- ----------- ----------- ----------- -----------
李四 65 77 65 85
张三 78 87 82 90

请问这该如何处理?另外问一下,怎么样发彩色的SQL语句啊?

[解决办法]
把你的语句选了,然后点击那个【插入源代码】。

SQL code
declare @s nvarchar(4000) Select @s=isnull(@s+',','')+quotename([Course]) from Class group by[Course] 

热点排行
Bad Request.