您的位置:首页 > 数据库

SQL交叉表的实例(横表转纵表)

2010-07-14 16:42 239 查看
很简单的一个东西,见网上好多朋友问“怎么实现交叉表?”,以下是我写的一个例子,数据库基于SQL SERVER 2000。
  
  交叉表实例
  
  建表:
  
  在查询分析器里运行:
  
  CREATE TABLE [Test] (
  
  [id] [int] IDENTITY (1, 1) NOT NULL ,
  
  [name] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
  
  [subject] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
  
  [Source] [numeric](18, 0) NULL
  
  ) ON [PRIMARY]
  
  GO
  
  INSERT INTO [test] ([name],[subject],[Source]) values (N'张三',N'语文',60)
  
  INSERT INTO [test] ([name],[subject],[Source]) values (N'李四',N'数学',70)
  
  INSERT INTO [test] ([name],[subject],[Source]) values (N'王五',N'英语',80)
  
  INSERT INTO [test] ([name],[subject],[Source]) values (N'王五',N'数学',75)
  
  INSERT INTO [test] ([name],[subject],[Source]) values (N'王五',N'语文',57)
  
  INSERT INTO [test] ([name],[subject],[Source]) values (N'李四',N'语文',80) [bitsCN.Com]
  
  INSERT INTO [test] ([name],[subject],[Source]) values (N'张三',N'英语',100)
  
  Go
  


 

  交叉表语句的实现:
  
  用于:交叉表的列数是确定的
  
  select name,sum(case subject when '数学' then source else 0 end) as '数学',
  
  sum(case subject when '英语' then source else 0 end) as '英语',
  
  sum(case subject when '语文' then source else 0 end) as '语文'
  
  from test
  
  group by name
  
  --用于:交叉表的列数是不确定的
  
  declare @sql varchar(8000)
  
  set @sql = 'select name,'
  
  select @sql = @sql + 'sum(case subject when '''+subject+'''
  
  then source else 0 end) as '''+subject+''','
  
  from (select distinct subject from test) as a
  
  select @sql = left(@sql,len(@sql)-1) + ' from test group by name'
  
  exec(@sql)
  
  go




  

MS Server的Analysis Services組件是專門用來做交叉表的處理

Microsoft SQL Server 2000 Analysis Services

自己***的过程:

CREATE Table allen_test(
  id NUMBER(8,0) NOT NULL ,  
  name VARCHAR2(30) NOT NULL ,  
  subject VARCHAR2(30) NOT NULL ,  
  Source NUMBER(8,2) ,
PRIMARY Key (Id)  
  );
COMMENT ON Column allen_test.Id IS '序号';
COMMENT ON Column allen_test.Name IS '姓名';
COMMENT ON Column allen_test.subject IS '学科';
COMMENT ON Column allen_test.Source IS '分数';
  
  INSERT Into allen_test values (1, '张三','语文',60);  
  INSERT INTO allen_test values (2, '李四','数学',70);  
  INSERT Into allen_test values (3, '王五','英语',80);   
  INSERT INTO allen_test values (4, '王五','数学',75);  
  INSERT INTO allen_test values (5, '王五','语文',57);  
  INSERT INTO allen_test values (6, '李四','语文',80) ;  
  INSERT INTO allen_test values (7, '张三','英语',100);
  

select name,
sum(case subject when '数学' then source else 0 end) As 数学,  
sum(case subject when '英语' then source else 0 end) as 英语,  
sum(case subject when '语文' then source else 0 end) as 语文  
from allen_test  
group by Name;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: