建表:
在查詢分析器裡執行:
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]
goinsert 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
交叉表例項
create table test id int identity 1,1 names nvarchar 50 subject nvarchar 50 source decimal 18,0 insert into test names subject source values n 張三 n 語文...
SQL交叉表的例項
很簡單的乙個東西,見網上好多朋友問 怎麼實現交叉表?以下是我寫的乙個例子,資料庫基於sql server 2000。交叉表例項 建表 在查詢分析器裡執行 create table test id int identity 1,1 not null name nvarchar 50 collate c...
詳細介紹SQL交叉表的例項
資料庫基於sql server 2000。交叉表例項 建表 在查詢分析器裡執行 create table test id int identity 1,1 not null name nvarchar 50 collate chinese prc ci as null subject nvarcha...