日期:2014-05-18 浏览次数:20559 次
if object_id ('dbo.table5') is not null drop table dbo.table5 go create table dbo.table5 ( id int not null, name varchar (32) null, k1 int null, k2 int null, k3 int null ) go insert into table5 select '1','张三','100','98','89' union all select '2','李四','79','77','85' union all select '3','王五','68','72','75' union all select '4','张三','97','95','98' union all select '5','王五','75','70','77' union all select '6','王五','80','76','73' declare @c varchar(500)='' declare @sql varchar(2000)='' select @c= isnull(',sum('+c.name+')','')+@c from sys.columns c join sys.objects o on c.object_id=o.object_id and o.name='table5' where c.name like 'k%' select @sql =stuff(@c,1,1,'') from t exec ('select name,'+@sql+' from table5 group by name')
------解决方案--------------------
IF EXISTS (SELECT 1 FROM SYSOBJECTS WHERE name = 'tba') BEGIN DROP TABLE tba END GO CREATE TABLE tba ( Id INT, Name VARCHAR(100), col1 INT, col2 INT, col3 INT ) GO INSERT INTO tba SELECT 1,'张三',100,89,48 UNION SELECT 2,'李四',89,88,48 UNION SELECT 3,'王五',87,87,43 UNION SELECT 4,'张三',79,86,47 UNION SELECT 5,'李四',58,85,46 UNION SELECT 6,'王五',89,84,55 GO DECLARE @sql VARCHAR(1000) = '' DECLARE @Total VARCHAR(1000) = '' SET @sql = 'SELECT Name' SELECT @sql = @sql + ',' + 'SUM(' + name + ') AS ' + name,@Total = @Total + '+' + 'SUM(' + name + ')' FROM Sys.columns WHERE object_name(object_id) = 'tba' and name NOT IN ('ID','Name') SET @sql = @sql + ',' + RIGHT(@Total,LEN(@Total) - 1) + ' AS Total' + ' FROM tba GROUP BY Name' EXEC (@Sql) Name col1 col2 col3 Total 李四 147 173 94 414 王五 176 171 98 445 张三 179 175 95 449
------解决方案--------------------
--> 测试数据:[test] if object_id('[test]') is not null drop table [test] create table [test]( [id] int, [姓名] varchar(4), [考试1] int, [考试2] int, [考试3] int ) go insert [test] select 1,'张三',100,98,89 union all select 2,'李四',79,77,85 union all select 3,'王五',68,72,75 union all select 4,'张三',97,95,98 union all select 5,'王五',75,70,77 union all select 6,'王五',80,76,73 go declare @str varchar(2000) set @str='' select @str=@str+',sum('+name+') as '+name from syscolumns where id=object_id('test') and name not in('id','姓名') declare @col varchar(2000) set @col='' select @col=@col+'+sum('+name+')' from syscolumns where id=object_id('test') and name not in('id','姓名') print @col set @str='select row_number()over(order by getdate()) as id,姓名' +@str+',(select '+RIGHT(@col,LEN(@col)-1)+' from test b where a.姓名=b.姓名)as 合计 from test a group by 姓名 ' exec( @str) /* id 姓名 考试1 考试2 考试3 合计 1 李四 79 77 85 241 2 王五 223 218 225 666 3 张三 197 193 187 577 */