Given the following table:
CREATE TABLE BitValues ( n int )
Is it possible to compute the bitwise-OR of n
for all rows within a subquery? For example, if BitValues contains these 4 rows:
+---+ | n | +---+ | 1 | | 2 | | 4 | | 3 | +---+
I would expect the subquery to return 7. Is there a way to do this inline, without creating a UDF?
Preparations:
Solution:
You can use a variable and do a "bitwise or" (
|
) for each row:This prints
7
. Note that assigning variables in a select is not officially supported.In a more strictly SQL way, you can create a table with one row for each bit. This table would have 31 rows, as the 32nd bit is a negative integer. This example uses a recursive CTE to create that table:
This sums the bits where any bit in the source table is set.
For me that is the best solution.
I see this post is pretty old and there are some useful answers but this is a pretty crazy straight forward method...
A simple solution which is a mix of @AlexKuznetsov's and @Andomar's solutions.
The bit mask is generated by a recursive Common Table Expression, but in a simpler way than in @Andomar's solution.
The bits are then summed just like in @AlexKuznetsov's solution.
In this example I assume a 16 bits mask is required, hence the 65536 limit. You can indicate a N-bits mask by changing 65536 to 2^N.
This is an alternative, without WITH (hurrah!!!):
Also consider a Group By example:
The first example is meant to be slower than WITH. However when you use GroupBy with some other data, the queries are largely the same cost-wise.
Another way to do this is
It's a bit worse because of repetition in code, a bit more readable and similar in execution cost.