复制代码 代码如下:
USE [master]
GO
/****** Object: Table [dbo].[Table_1] Script Date: 08/06/2013 13:55:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Table_1](
[name] [varchar](50) NOT NULL,
[score] [real] NOT NULL,
[subject_id] [int] NOT NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
复制代码 代码如下:
insert into [master].[dbo].[Table_1] ([name],[score],[subject_id]) values( '张三' , 90 , 1 );
insert into [master].[dbo].[Table_1] ([name],[score],[subject_id]) values( '张三' , 80 , 2 );
insert into [master].[dbo].[Table_1] ([name],[score],[subject_id]) values( '张三' , 70 , 3 );
insert into [master].[dbo].[Table_1] ([name],[score],[subject_id]) values( '王五' , 50 , 1 );
insert into [master].[dbo].[Table_1] ([name],[score],[subject_id]) values( '王五' , 40 , 2 );
insert into [master].[dbo].[Table_1] ([name],[score],[subject_id]) values( '李四' , 60 , 1 );
复制代码 代码如下:
SELECT [name],[1],[2],[3]
FROM [master].[dbo].[Table_1]
pivot
(
sum(score) for subject_id in ([1],[2],[3])
) as pvt
GO
复制代码 代码如下:
SELECT [name],[subject_id],[score]
FROM
(
SELECT [name],[1],[2],[3]
FROM [master].[dbo].[Table_1]
pivot
(
sum(score) for subject_id in ([1],[2],[3])
) as pvt
) p
unpivot
(
score for subject_id in([1],[2],[3])
) as unpvt
新闻热点
疑难解答