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语句啊?
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语句啊?
Select @s=isnull(@s+',','')+quotename([Course]) from Class group by[Course] 这里价格order by试过没?