小编典典

T-SQL中的汉明重量/人口计数

sql

我正在寻找一种计算BINARY(1024)字段的汉明权重/人口计数/“ 1位数”的 快速
方法。MySQL有一个类似的BIT_COUNT函数。我在T-SQL中找不到类似的功能?

还是建议将二进制数据存储在其他类型的字段中?

如果您不知道我在说什么,这是Wikipedia上有关海明重量的文章


阅读 174

收藏
2021-05-05

共1个答案

小编典典

您可以使用具有预先计算的汉明权重的助手表来获取较小的数字(例如字节),然后相应地拆分值,加入助手表并获得部分汉明权重之和作为该值的汉明权重:

-- define Hamming weight helper table
DECLARE @hwtally TABLE (byte tinyint, hw int);
INSERT INTO @hwtally (byte, hw) VALUES (0, 0);
INSERT INTO @hwtally (byte, hw) SELECT   1 - byte, 1 - hw FROM @hwtally;
INSERT INTO @hwtally (byte, hw) SELECT   3 - byte, 2 - hw FROM @hwtally;
INSERT INTO @hwtally (byte, hw) SELECT   7 - byte, 3 - hw FROM @hwtally;
INSERT INTO @hwtally (byte, hw) SELECT  15 - byte, 4 - hw FROM @hwtally;
INSERT INTO @hwtally (byte, hw) SELECT  31 - byte, 5 - hw FROM @hwtally;
INSERT INTO @hwtally (byte, hw) SELECT  63 - byte, 6 - hw FROM @hwtally;
INSERT INTO @hwtally (byte, hw) SELECT 127 - byte, 7 - hw FROM @hwtally;
INSERT INTO @hwtally (byte, hw) SELECT 255 - byte, 8 - hw FROM @hwtally;

-- calculate
WITH split AS (
  SELECT SUBSTRING(@value, number, 1) AS byte
  FROM master.dbo.spt_values
  WHERE type = 'P' AND number BETWEEN 1 AND LEN(@value)
)
SELECT
  Value = @value,
  HammingWeight = SUM(t.hw)
FROM split s
  INNER JOIN @hwtally t ON s.byte = t.byte
2021-05-05