SQL中的负数就像excel一样
我在复制SQL服务器中的mod函数时遇到了问题。
在excel中,mod(-3,7)= 4。但在SQL中,-3%7 = -3
我使用%错误,还是SQL做不同的mod?
对于x的正值和负值,这将给出0和n – 1之间的结果:
((x % n) + n) % n
那么, 模块化algorithm是在整数的等价类上完成的,所以Excel和任何RDBMS都不是“做错了”。 如果你想要一个0到6之间的代表,你可以随时做
select (-3 % 7) + 7;
敢于沉闷(晚会到晚会)。
declare @Modulus as Int = 7 declare @Samples as Table ( Value Int ) insert into @Samples ( Value ) values ( -12 ), ( -3 ), ( 0 ), ( 3 ), ( 13 ), ( 70 ) select Value, case Sign( Value ) when 1 then Value % @Modulus when -1 then Value % @Modulus + @Modulus else 0 end as Modulus from @Samples