Bitwise operation in Group By

ぐ巨炮叔叔 提交于 2020-08-09 16:04:30

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/27902765/bitwise-operation-in-group-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!