SQL:如何对一行中的多个位列求和

时间:2016-09-13 17:30:19

标签: sql sql-server sum type-conversion

我的数据结构每行都有重复的位列

enter image description here

如何获得每行的真实总数?例如
Id总计
03 2
17 0
21 3
24 2

4 个答案:

答案 0 :(得分:2)

出于教育目的,此处的版本为UNPIVOT

DECLARE @t TABLE (id INT, ok1112 bit, ok1213 BIT, ok1314 BIT, ok1415 BIT, ok1516 BIT)
INSERT INTO @t VALUES
(3, 1, 1, 0, 0, 0),
(17, 0, 0, 0, 0, 0),
(21, 0, 0, 1, 1, 1),
(24, 1, 1, 0, 0, 0)

SELECT id, SUM(CAST(a AS int)) AS Total
FROM @t
UNPIVOT(a FOR b IN(ok1112, ok1213, ok1314, ok1415, ok1516))u
GROUP BY id

答案 1 :(得分:1)

bit转换为Int并执行算术运算

select id,cast([Ok_1112] as Int)+cast([Ok_1213] as Int)+...
From yourtable

答案 2 :(得分:1)

如果您有大量OK字段,并且不想对其进行编码,请尝试以下

Declare @YourTable table (Id int,OK_1112 bit,OK_1213 bit,OK_1314 bit,OK_1415 bit,OK_1516 bit)
Insert into @YourTable values
(3 ,1,1,0,0,0),
(17,0,0,0,0,0),
(21,0,0,1,1,1),
(24,1,1,0,0,0)

Declare @XML xml
Set @XML = (Select * from @YourTable for XML RAW)

Select ID,Total=Sum(cast(Value as int))
 From (
        Select ID    = r.value('@Id','int')
              ,Item  = attr.value('local-name(.)','varchar(100)')
              ,Value = attr.value('.','varchar(max)') 
         From  @XML.nodes('/row') as A(r)
         Cross Apply A.r.nodes('./@*[local-name(.)!="Id"]') as B(attr)
      ) A
 Group By ID

返回

ID  Total
3   2
17  0
21  3
24  2

仅供参考,如果您只是运行子查询,您将看到以下内容

ID  Item    Value
3   OK_1112 1
3   OK_1213 1
3   OK_1314 0
3   OK_1415 0
3   OK_1516 0
17  OK_1112 0
17  OK_1213 0
17  OK_1314 0
17  OK_1415 0
17  OK_1516 0
21  OK_1112 0
21  OK_1213 0
21  OK_1314 1
21  OK_1415 1
21  OK_1516 1
24  OK_1112 1
24  OK_1213 1
24  OK_1314 0
24  OK_1415 0
24  OK_1516 0

答案 3 :(得分:0)

以下查询应该为您提供MS SQL中所需的输出。

select id , (convert (int,OK_1112) + convert (int,OK_1213) + convert (int,OK_1314)+convert (int,OK_1516)) AS total from Table_Name

此处,id列位于 int 中,列OK_1112,OK_1213,OK_1314,OK_1516属于