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

SQL:如何对一行中的多个位列求和,sql,sql-server,sum,type-conversion,Sql,Sql Server,Sum,Type Conversion,我有一个数据结构,每行有重复的位列 如何获得每行的True总数?例如 Id总数 032 17 0 21.3 24 2将位强制转换为Int,然后进行算术运算 select id,cast([Ok_1112] as Int)+cast([Ok_1213] as Int)+... From yourtable 出于教育目的,这里是带有UNPIVOT的版本: DECLARE @t TABLE (id INT, ok1112 bit, ok1213 BIT, ok1314 BIT, ok1415 B

我有一个数据结构,每行有重复的位列

如何获得每行的True总数?例如
Id总数
032
17 0
21.3

24 2

强制转换为
Int
,然后进行算术运算

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

出于教育目的,这里是带有
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

如果有大量“确定”字段,并且不想对其进行编码,请尝试以下操作

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  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
返回

ID  Total
3   2
17  0
21  3
24  2
仅供参考如果您只是运行子查询,您将看到以下内容

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  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

下面的查询应提供所需的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列的类型为