如何在SQL Server中对多列的值求和

时间:2016-12-31 18:50:35

标签: sql sql-server

SELECT 
    name 
FROM 
    sys.all.column 
WHERE object_id = (SELECT object_id 
                   FROM sys.all_objects 
                   WHERE name ='name of my table' and type = 'TT') 
  AND name NOT IN (list of columns that I don't need)

如何汇总前面SQL查询中返回列的所有值?

3 个答案:

答案 0 :(得分:2)

另一个选项不需要动态SQL,只需要一个CROSS APPLY或两个

为了好玩,我添加Min,Max和Avg只是为了说明...还添加了PctOfTotal或Common-Size

Declare @YourTable table (ID int,CustName varchar(50),Sales_Jan int,Sales_Feb int,Sales_Mar int)
Insert into @YourTable values
(1,'John Smith',25,25,50),
(2,'Jane Doe'  ,35,20,null)

Select A.*
      ,C.*
      ,PctOfTotal = Format(C.Total*1.0/Sum(C.Total) over (),'0.00%')
 From  @YourTable A
 Cross Apply (Select XMLData=cast((Select A.* For XML RAW) as xml)) B
 Cross Apply (
                Select Total = Sum(Value)
                      ,Min   = Min(Value)
                      ,Max   = Max(Value)
                      ,Avg   = Avg(Value)
                 From  (
                        Select Value  = attr.value('.','int') 
                         From  B.XMLData.nodes('/row') as A(r)
                         Cross Apply A.r.nodes('./@*') AS B(attr)
                         Where attr.value('local-name(.)','varchar(100)') Like 'Sales_%'
                         --Or you can Exclude Specific Columns
                         --Where attr.value('local-name(.)','varchar(100)') not in ('ID','CustName')
                       ) S
             ) C

返回

enter image description here

答案 1 :(得分:1)

如果我理解正确,您希望从元数据表中找出要求和的一些列,然后在给定表上对这些列求和。您可以使用动态SQL来实现此目的:

create table t(a integer, b integer, c integer);

insert into t values(1,2,3);

declare @tab varchar(100);
declare @sql varchar(max);
set @sql = '';
set @tab = 't';

select @sql = @sql + '+' + a.name from sys.all_columns a
inner join 
sys.all_objects b
on a.object_id = b.object_id
where b.name = @tab
and a.name not in ('c');

set @sql = 'select ' + stuff(@sql, 1, 1, '') + ' from ' + @tab;

exec(@sql);

产地:

3

答案 2 :(得分:0)

select col1,col2,col3,col4,NVL(col1,0)+NVL(col2,0)+NVL(col3,0)+NVL(col4,0)
from
(select *
from sys.all.column
where object_id =(select object_id from sys.all.object where name ='name of my table') 
  and name not in (list of columns that I dont need).)


   A  |  B   |  Total(col1+col2)
------+------+-------
   1  |  2   |   3
---------------------
   1  |      |   1

无论您获得哪些列,请将其求和,并将它们作为单独的列放在结果表中。