ehxz 发表于 2006-12-18 22:47:40

详细介绍SQL交叉表的实例

  很简单的一个东西,见网上好多朋友问“怎么实现交叉表?”,以下是我写的一个例子,数据库基于SQL SERVER 2000。<br />  <br />  交叉表实例<br />  <br />  建表:<br />  <br />  在查询分析器里运行:<br />  <br />  CREATE TABLE (<br />  <br />   IDENTITY (1, 1) NOT NULL ,<br />  <br />   (50) COLLATE Chinese_PRC_CI_AS NULL ,<br />  <br />   (50) COLLATE Chinese_PRC_CI_AS NULL ,<br />  <br />   (18, 0) NULL<br />  <br />  ) ON <br />  <br />  GO<br />  <br />  INSERT INTO (,,) values (N'张三',N'语文',60)<br />  <br />  INSERT INTO (,,) values (N'李四',N'数学',70)<br />  <br />  INSERT INTO (,,) values (N'王五',N'英语',80)<br />  <br />  INSERT INTO (,,) values (N'王五',N'数学',75)<br />  <br />  INSERT INTO (,,) values (N'王五',N'语文',57)<br />  <br />  INSERT INTO (,,) values (N'李四',N'语文',80)<br />  <br />  INSERT INTO (,,) values (N'张三',N'英语',100)<br />  <br />  Go<br />   <center>  </center><br />  交叉表语句的实现:<br />  <br />  用于:交叉表的列数是确定的<br />  <br />  select name,sum(case subject when '数学' then source else 0 end) as '数学',<br />  <br />  sum(case subject when '英语' then source else 0 end) as '英语',<br />  <br />  sum(case subject when '语文' then source else 0 end) as '语文'<br />  <br />  from test<br />  <br />  group by name<br />  <br />  --用于:交叉表的列数是不确定的<br />  <br />  declare @sql varchar(8000)<br />  <br />  set @sql = 'select name,'<br />  <br />  select @sql = @sql + 'sum(case subject when '''+subject+'''<br />  <br />  then source else 0 end) as '''+subject+''','<br />  <br />  from (select distinct subject from test) as a<br />  <br />  select @sql = left(@sql,len(@sql)-1) + ' from test group by name'<br />  <br />  exec(@sql)<br />  <br />  go<br />  <br />  运行结果:<br />   <center> </center>
页: [1]
查看完整版本: 详细介绍SQL交叉表的实例