需要根据行计算sum()

时间:2016-01-01 10:41:19

标签: sql sql-server tsql

需要逐行计算总和

S1  S2  S3  S4  S5  
0   0   1   0   1  
0   1   1   1   1  
1   1   1   1   0  
0   1   0   0   0    

欲望输出

S1  S2  S3  S4  S5  SUM  
0   0   1   0   1   2  
0   1   1   1   1   4  
1   1   1   1   0   4  
0   1   0   0   0   1  

提前致谢。

5 个答案:

答案 0 :(得分:3)

一个简单的解决方案是进行下一个查询:

select s1, s2, s3, s4, s5,isnull(s1,0) + isnull(s2,0) + isnull(s3,0) + isnull(s4,0) + isnull(s5,0) as Total
from table

http://sqlfiddle.com/#!3/5f68a/2

答案 1 :(得分:2)

试试这个 -

<强>模式

DECLARE @table1 TABLE 
(
  s1 int,
  s2 int,
  s3 int,
  s4 int
)

INSERT INTO @table1  VALUES(0,   0,   1,   0)   
INSERT INTO @table1  VALUES(0,   1,   1,   1)
INSERT INTO @table1  VALUES(1,   1,   1,   1)
INSERT INTO @table1  VALUES(0,   1,   1,   0)

<强>查询

SELECT s1, s2, s3, s4, 
(
    SELECT SUM(TotalCnt) FROM (VALUES (s1), (s2), (s3), (s4)) as t(TotalCnt)
) as [Sum]
FROM @table1

<强>结果

s1  s2  s3  s4  Sum
0   0   1   0   1
0   1   1   1   3
1   1   1   1   4
0   1   1   0   2

SQL Fiddle

答案 2 :(得分:2)

使用简单的添加:

SELECT s1, s2, s3, s4, s5,
       [SUM] =  s1 + s2 + s3 + s4 + s5
FROM table;

如果任何列可以为空,请用COALESCE(sN, 0)包裹它。

LiveDemo

<小时/> 为避免使用NULL处理ISNULL/CASE/COALESCE/IIF,您可以使用SUMCROSS APPLY

SELECT s1, s2, s3, s4, s5, sub.[sum]
FROM #tab
CROSS APPLY(SELECT SUM(c) 
            FROM (VALUES (s1), (s2), (s3), (s4), (s5)) AS s(c)
            ) AS sub([sum])

LiveDemo2

答案 3 :(得分:1)

只需+

<强>查询

SELECT s1, s2, s3, s4, s5,
s1 + s2 + s3 + s4 + s5 AS [SUM]
from tblNum;

<强> Fiddle demo

答案 4 :(得分:0)

试试这个: -

 SELECT  [S1] ,[S2],[S3] ,[S4],[S5], sum(S1+S2+S3+S4+S5) as sum
  FROM TableName
  group by [S1],[S2],[S3] ,[S4],[S5]

SQL Fiddle