程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫

sql列轉行

編輯:關於SqlServer

       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

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

      declare @sql varchar(8000)

      set @sql = 'select id,'

      select @sql = @sql + '(case subject when '''+subject+'''

      then source else null end) as '''+subject+''','

      from (select distinct subject from test) as a

      select @sql = left(@sql,len(@sql)-1) + ' from test '

      exec(@sql)

      go

    1. 上一頁:
    2. 下一頁:
    Copyright © 程式師世界 All Rights Reserved