I have a data structure that has repeating bit columns per row
How to I get the total number of Trues for each row? For example
Id Total
03 2
17 0
21 3
24 2
Cast the bit
to Int
and do the arithmetic operation
select id,cast([Ok_1112] as Int)+cast([Ok_1213] as Int)+...
From yourtable
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With