詳細介紹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

  

  交叉表語句的實現:

  用於:交叉表的列數是確定的

  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

  運行結果:


  

插入數據的另一種寫法:

Insert Class
select N'張三',N'國語',78 union all
select N'張三',N'數學',87 union all
select N'張三',N'英語',82 union all
select N'張三',N'物理',90 union all
select N'李四',N'國語',65 union all
select N'李四',N'數學',77 union all
select N'李四',N'英語',65 union all
select N'李四',N'物理',85

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章