As part of a complex aggregate I want to know the bitwise sum of some data, i.e. if I have rows with values 1,1,1,2,2,8 the bitwise sum is 11. In this case the values are all exact powers of two (single bits), so I can hack around it by grouping and summing over the groups (obviously this example is a bit tortured compared to the real query):
select SUM(y.test)
from (
select x.test
from ( -- garbage test data
select 1 as [test]
union all select 1
union all select 1
union all select 2
union all select 2
union all select 8) x
group by x.test) y
but is there a clean way to perform a bitwise sum in [T]SQL?
Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be obtained by performing AND (&) of two bits. Above is simple Half Adder logic that can be used to add 2 single bits. We can extend this logic for integers.
Given an array “arr[0..n-1]” of integers. The task is to calculate the sum of Bitwise OR of all pairs, i.e. calculate the sum of “arr[i] | arr[j]” for all the pairs in the given array where i < j. Here '|' is a bitwise OR operator.
Sum of two bits can be performed using the XOR ^ operator and carry bit can be obtained by using AND & operator. Provided a and b don't have set bits at the same position, then using ^ operator gives the sum of a and b .
Addition and bit-wise or would be the same as bit-wise or would include any bits in either, and normal addition would do exactly the same given the mutually exclusive nature of your bits.
You have the operator | which performs bitwise or for 2 operands. It is possible to solve your problem using a cursor and this operator.
Edit yes I mixed up and and or, fixed.
If all of your test values are single bits as in your example (1, 2, 8) - simply use SUM(DISTINCT col)
in your query.
Hope that helps.
(For reference: http://msdn.microsoft.com/en-us/library/ms187810.aspx)
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