使用 t-sql 计算二进制类型的真位数

Mos*_*ndi 2 sql t-sql binary count varbinary

我需要找出我的二进制值中存在多少真位。

例子:

input: 0001101    output:3
input: 1111001    output:5
Run Code Online (Sandbox Code Playgroud)

小智 5

虽然两个答案都有效,但都有问题。循环不是最优的并且会破坏该值。这两种解决方案都不能在 select 语句中使用。

可能更好的解决方案是按如下方式一起屏蔽

select @counter = 0 
+ case when @BinaryVariable2 & 1 = 1 then 1 else 0 end 
+ case when @BinaryVariable2 & 2 = 2 then 1 else 0 end 
+ case when @BinaryVariable2 & 4 = 4 then 1 else 0 end 
+ case when @BinaryVariable2 & 8 = 8 then 1 else 0 end 
+ case when @BinaryVariable2 & 16 = 16 then 1 else 0 end 
+ case when @BinaryVariable2 & 32 = 32 then 1 else 0 end 
+ case when @BinaryVariable2 & 64 = 64 then 1 else 0 end 
+ case when @BinaryVariable2 & 128 = 128 then 1 else 0 end 
+ case when @BinaryVariable2 & 256 = 256 then 1 else 0 end 
+ case when @BinaryVariable2 & 512 = 512 then 1 else 0 end 
Run Code Online (Sandbox Code Playgroud)

这可以在选择和更新语句中使用。它也快了一个数量级。(在我的服务器上大约 50 次)

为了帮助您可能需要使用以下生成器代码

declare @x int = 1, @c int = 0
print ' @counter = 0 '  /*CHANGE field/parameter name */
while @c < 10  /* change to how many bits you want to see */
begin
print ' + case when @BinaryVariable2 & ' + cast(@x as varchar) + ' = ' + cast(@x as varchar) + ' then 1 else 0 end '   /* CHANGE the variable/field name */
select @x *=2, @c +=1
end 
Run Code Online (Sandbox Code Playgroud)

另请注意:如果您使用 bigint 或超过 32 位,则必须按如下方式进行转换

print ' + case when @Missing & cast(' + cast(@x as varchar) + ' as bigint) = ' + cast(@x as varchar) + ' then 1 else 0 end '
Run Code Online (Sandbox Code Playgroud)

享受