日期:2014-05-18 浏览次数:20476 次
declare @str varchar(2000) set @str='' select @str=@str+',sum('+name+') as '+name from syscolumns where id=object_id('JXhuizong') and name not in('id','JXtime','姓名') declare @col varchar(2000) set @col='' select @col=@col+'+sum('+name+')' from syscolumns where id=object_id('JXhuizong') and name not in('id','JXtime','姓名') print @col set @str='select row_number()over(order by getdate()) as id,姓名' +@str+',(select '+RIGHT(@col,LEN(@col)-1)+' from JXhuizong b where a.姓名=b.姓名 and JXtime='''+@JXtime+''')as 加减总分 from JXhuizong a where JXtime='''+@JXtime+''' group by 姓名 ' exec( @str)
case sum(col)=0 then '' else ltrim(sum(col))
------解决方案--------------------
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,0,48 UNION SELECT 2,'李四',89,0,48 UNION SELECT 3,'王五',87,0,43 UNION SELECT 4,'张三',79,0,47 UNION SELECT 5,'李四',58,0,46 UNION SELECT 6,'王五',89,0,55 GO DECLARE @sql VARCHAR(1000) = '' DECLARE @Total VARCHAR(1000) = '' DECLARE @ColumnNames TABLE (ID INT IDENTITY(1,1),ColumnName VARCHAR(100)) declare @num int, @sqls nvarchar(4000) DECLARE @Line INT = 1 DECLARE @TotalNum INT DECLARE @ColumnName VARCHAR(100) INSERT INTO @ColumnNames SELECT name FROM Sys.columns WHERE object_name(object_id) = 'tba' and name NOT IN ('ID','Name') SELECT @TotalNum = MAX(ID) FROM @ColumnNames WHILE @Line <= @TotalNum BEGIN SELECT @ColumnName = ColumnName FROM @ColumnNames WHERE ID = @Line set @sqls='select @a=SUM(' + @ColumnName + ') from tba ' exec sp_executesql @sqls,N'@a int output',@num output IF @num = 0 BEGIN DELETE FROM @ColumnNames WHERE ID = @Line END SET @Line = @Line + 1 END SET @sql = 'SELECT Name' SELECT @sql = @sql + ',' + 'SUM(' + ColumnName + ') AS ' + ColumnName,@Total = @Total + '+' + 'SUM(' + ColumnName + ')' FROM @ColumnNames SET @sql = @sql + ',' + RIGHT(@Total,LEN(@Total) - 1) + ' AS Total' + ' FROM tba GROUP BY Name' EXEC (@Sql) Name col1 col3 Total 李四 147 94 241 王五 176 98 274 张三 179 95 274