需要逐行计算总和
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
提前致谢。
答案 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
答案 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
答案 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
,您可以使用SUM
和CROSS 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]