CREATE TABLE [Test_xcmtmp] (
[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_xcmtmp] ([name],[subject],[Source]) values (N'张三',N'语文',60)
INSERT INTO [Test_xcmtmp] ([name],[subject],[Source]) values (N'李四',N'数学',70)
INSERT INTO [Test_xcmtmp] ([name],[subject],[Source]) values (N'王五',N'英语',80)
INSERT INTO [Test_xcmtmp] ([name],[subject],[Source]) values (N'王五',N'数学',75)
INSERT INTO [Test_xcmtmp] ([name],[subject],[Source]) values (N'王五',N'语文',57)
INSERT INTO [Test_xcmtmp] ([name],[subject],[Source]) values (N'李四',N'语文',80)
INSERT INTO [Test_xcmtmp] ([name],[subject],[Source]) values (N'张三',N'英语',90)
Go
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_xcmtmp) as a
select @sql = left(@sql,len(@sql)-1) + ' from Test_xcmtmp group by name'
--**********
exec(@sql)
go
(1)string ConnString = "server=localhost;integrated security=sspi;database=pubs;";
(2)string strConnection="user uid=sa;pwd=123456;Database=test;Server=test;Connect ......