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?
It turned out that subqueries are not allowed in aggregate functions.
Except for the COUNT() function, SQL aggregate functions ignore null. You can use aggregate functions as expressions only in the following: The select list of a SELECT statement, either a subquery or an outer query.
An aggregate function can be used in a WHERE clause only if that clause is part of a subquery of a HAVING clause and the column name specified in the expression is a correlated reference to a group. If the expression includes more than one column name, each column name must be a correlated reference to the same group.
An aggregate query is a method of deriving group and subgroup data by analysis of a set of individual data entries. The term is frequently used by database developers and database administrators.
WITH Bits AS ( SELECT 1 AS BitMask UNION ALL SELECT 2 UNION ALL SELECT 4 UNION ALL SELECT 8 UNION ALL SELECT 16 ) SELECT SUM(DISTINCT BitMask) FROM ( SELECT 1 AS n UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 ) AS t JOIN Bits ON t.n & Bits.BitMask > 0
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