版权声明:csdn是本blog托管服务提供商。如本文牵涉版权问题,csdn不承担相关责任,请版权拥有者直接与文章作者联系解决。
sql交叉表实例
很简单的一个东西,见网上好多朋友问“怎么实现交叉表?”,以下是我写的一个例子,数据库基于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)
insert into [test] ([name],[subject],[source]) values (n'张三',n'英语',100)
go
450)this.width=450" o:title="sql2">
交叉表语句的实现:
--用于:交叉表的列数是确定的
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
运行结果:
450)this.width=450" o:title="sql">