WEB开发网
开发学院数据库MSSQL Server SQL2005中利用PIVOT实现分组统计 阅读

SQL2005中利用PIVOT实现分组统计

 2009-10-30 00:00:00 来源:WEB开发网   
核心提示: select[Student],[数学],[英语],[中文],([数学]+[英语]+[中文])AS总分FROM(SELECT[Student],[Score],[Subject]FROM[StudentsScore])ASTPIVOT(sum([Score])FOR[Subject]IN([数学

select [Student],[数学],[英语],[中文],([数学]+[英语]+[中文]) AS 总分 FROM (SELECT [Student],[Score],[Subject] FROM [StudentsScore]) AS T PIVOT(sum([Score]) FOR [Subject] IN ( [数学], [英语], [中文])) AS thePivot ORDER BY [Student]    

这样一来,在列数已知的情况下,我们就可以直接构造类似的语句,而不需要定义变量。

下面是本文中用到的数据表及数据记录的SQL,方便大家测试。

数据表脚本:

/****** 对象:  Table [dbo].[StudentsScore]    脚本日期: 10/29/2009 22:56:18 ******/   
SET ANSI_NULLS ON  
GO   
SET QUOTED_IDENTIFIER ON  
GO   
SET ANSI_PADDING ON  
GO   
CREATE TABLE [dbo].[StudentsScore](   
    [Student] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,   
    [Subject] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL,   
    [Score] [int] NULL  
) ON [PRIMARY]   
  
GO   
SET ANSI_PADDING OFF  

数据记录脚本:

Insert into StudentsScore (Student,Subject,Score) values ( '学生A', '中文', 80 );    
Insert into StudentsScore (Student,Subject,Score) values ( '学生A', '数学', 78 );    
Insert into StudentsScore (Student,Subject,Score) values ( '学生A', '英语', 92 );    
Insert into StudentsScore (Student,Subject,Score) values ( '学生B', '中文', 89 );    
Insert into StudentsScore (Student,Subject,Score) values ( '学生B', '数学', 87 );    
Insert into StudentsScore (Student,Subject,Score) values ( '学生B', '英语', 75 );    
Insert into StudentsScore (Student,Subject,Score) values ( '学生C', '中文', 92 );    
Insert into StudentsScore (Student,Subject,Score) values ( '学生C', '数学', 74 );    
Insert into StudentsScore (Student,Subject,Score) values ( '学生C', '英语', 65 );    
Insert into StudentsScore (Student,Subject,Score) values ( '学生D', '中文', 79 );    
Insert into StudentsScore (Student,Subject,Score) values ( '学生D', '数学', 83 );    
Insert into StudentsScore (Student,Subject,Score) values ( '学生D', '英语', 81 );    
Insert into StudentsScore (Student,Subject,Score) values ( '学生E', '中文', 73 );    
Insert into StudentsScore (Student,Subject,Score) values ( '学生E', '数学', 84 );    
Insert into StudentsScore (Student,Subject,Score) values ( '学生E', '英语', 93 );    
Insert into StudentsScore (Student,Subject,Score) values ( '学生F', '中文', 79 );    
Insert into StudentsScore (Student,Subject,Score) values ( '学生F', '数学', 86 );    
Insert into StudentsScore (Student,Subject,Score) values ( '学生F', '英语', 84 );   

上一页  1 2 3 

Tags:SQL 利用 PIVOT

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接