Nusret Parlak
Nusret Parlak

Reputation: 83

Bitwise operation in Group By

I must use bitwise operations in a group by query but I didn't found anything.

Table:

PermissionId, BitMask(BigInt)
1,            4
2,            7
1,            8
1,            5

I want results as:

1,           13
2,           7

How can I write this script in T-SQL as below

SELECT PermissionId, BIT_OR(BitMask)
FROM table
GROUP BY PermissionId

Upvotes: 2

Views: 2331

Answers (1)

t-clausen.dk
t-clausen.dk

Reputation: 44326

Your question just became very interesting.

Create this function(you may want to reconsider the name)

CREATE function f_test
(
  @param bigint
)
  returns @t table (value bigint)
AS
BEGIN

;WITH CTE AS
(
  SELECT
    @param % 2 value, 
    1 multiplier, 
    @param / 2 remain
  UNION ALL
  SELECT
    remain % 2, 
    multiplier * 2,
    remain / 2
  FROM
    CTE
  WHERE
    remain > 0
)
INSERT @t
SELECT multiplier 
FROM CTE
WHERE value = 1
RETURN

END

Now you can run this script, I am using a table variable, replace it with your table:

DECLARE @t table(PermissionId int, BitMask bigint)
INSERT  @t values(1,4),(2,7),(1,8),(1,5)

SELECT
  t1.PermissionId, 
  SUM(distinct t2.Value) Total
FROM
  @t t1
CROSS APPLY
f_test(t1.BitMask) t2
GROUP BY
  t1.PermissionId

Result:

PermissionId  Total
1             13
2             7

Upvotes: 2

Related Questions