CREATE TABLE TestTable( [Id] [int] IDENTITY(1,1) NOT NULL, [UserName] [nvarchar](50) NULL, [Subject] [nvarchar](50) NULL, [Source] [numeric](18, 0) NULL ) ON [PRIMARY] go INSERT INTO TestTable ([UserName],[Subject],[Source]) SELECT N'張三',N'語文',60 UNION ALL SELECT N'李四',N'數學',70 UNION ALL SELECT N'王五',N'英語',80 UNION ALL SELECT N'王五',N'數學',75 UNION ALL SELECT N'王五',N'語文',57 UNION ALL SELECT N'李四',N'語文',80 UNION ALL SELECT N'張三',N'英語',100 GO
這裏我用了三種方法來實現行轉列第一種:靜態行轉列sql
select UserName 姓名, sum(case Subject when '語文' then Source else 0 end) 語文,sum(case Subject when '數學' then Source else 0 end) 數學,
sum(case Subject when '英語' then Source else 0 end) 英語 from TestTable group by UserName
用povit行轉列數據庫
select * from (select UserName,Subject,Source from TestTable) testpivot(sum(Source) for Subject in(語文,數學,英語) ) pvt
用存儲過程行轉列spa
alter proc pro_test @userImages varchar(200), @Subject varchar(20), @Subject1 varchar(200), @TableName varchar(50) as declare @sql varchar(max)='select * from (select '+@userImages+' from'+@TableName+') tab pivot ( sum('+@Subject+') for Subject('+@Subject1+') ) pvt' exec (@sql) go
exec pro_test 'UserName,Subject,Source',
'TestTable',
'Subject',
'語文,數學,英語'
它們的效果都是這樣的3d
以上三種方式實現行轉列,咱們能夠根據本身的需求採用不一樣的方法code