Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aggregate bitwise-OR in a subquery

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?

like image 582
Daniel Avatar asked Oct 20 '10 18:10

Daniel


People also ask

Can we use aggregate function in subquery?

It turned out that subqueries are not allowed in aggregate functions.

Can we use aggregate function with query syntax?

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.

Can we aggregate function in where clause?

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.

What are aggregates in queries?

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.


1 Answers

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 
like image 112
A-K Avatar answered Sep 17 '22 15:09

A-K