Marc Gravell Marc Gravell - 5 months ago 18
SQL Question

Performing a bitwise sum

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?

Answer

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)