Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL : How to sum multiple bit columns in a row

I have a data structure that has repeating bit columns per row

enter image description here

How to I get the total number of Trues for each row? For example
Id Total
03 2
17 0
21 3
24 2

like image 839
Ash Machine Avatar asked Sep 13 '16 17:09

Ash Machine


2 Answers

Cast the bit to Int and do the arithmetic operation

select id,cast([Ok_1112] as Int)+cast([Ok_1213] as Int)+...
From yourtable
like image 103
Pரதீப் Avatar answered Sep 29 '22 05:09

Pரதீப்


For educational purposes here is the version with 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
like image 21
Giorgi Nakeuri Avatar answered Sep 29 '22 07:09

Giorgi Nakeuri