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

前端之家收集整理的这篇文章主要介绍了汉明重量/人口数量在T-SQL中前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在寻找一种快速计算BINARY(1024)字段的汉明重量/总体数/“1位数”的方法. MysqL有一个BIT_COUNT函数可以做类似的事情.我在T-sql中找不到类似的功能

或者您是否建议将二进制数据存储在另一种类型的字段中?

如果你不知道我在说什么,这里是Wikipedia article about the hamming weight.

解决方法

您可以使用具有预先计算的汉明权重的辅助表来获取小数字(如字节),然后相应地拆分值,连接到辅助表并获得部分汉明权重的总和作为值的汉明权重:
  1. -- define Hamming weight helper table
  2. DECLARE @hwtally TABLE (byte tinyint,hw int);
  3. INSERT INTO @hwtally (byte,hw) VALUES (0,0);
  4. INSERT INTO @hwtally (byte,hw) SELECT 1 - byte,1 - hw FROM @hwtally;
  5. INSERT INTO @hwtally (byte,hw) SELECT 3 - byte,2 - hw FROM @hwtally;
  6. INSERT INTO @hwtally (byte,hw) SELECT 7 - byte,3 - hw FROM @hwtally;
  7. INSERT INTO @hwtally (byte,hw) SELECT 15 - byte,4 - hw FROM @hwtally;
  8. INSERT INTO @hwtally (byte,hw) SELECT 31 - byte,5 - hw FROM @hwtally;
  9. INSERT INTO @hwtally (byte,hw) SELECT 63 - byte,6 - hw FROM @hwtally;
  10. INSERT INTO @hwtally (byte,hw) SELECT 127 - byte,7 - hw FROM @hwtally;
  11. INSERT INTO @hwtally (byte,hw) SELECT 255 - byte,8 - hw FROM @hwtally;
  12.  
  13. -- calculate
  14. WITH split AS (
  15. SELECT SUBSTRING(@value,number,1) AS byte
  16. FROM master.dbo.spt_values
  17. WHERE type = 'P' AND number BETWEEN 1 AND LEN(@value)
  18. )
  19. SELECT
  20. Value = @value,HammingWeight = SUM(t.hw)
  21. FROM split s
  22. INNER JOIN @hwtally t ON s.byte = t.byte

猜你在找的MsSQL相关文章