Mod negative numbers in SQL just like excel

前端 未结 2 378
再見小時候
再見小時候 2020-12-11 15:46

I\'m having trouble replicating the mod function in SQL sever.

In excel, mod (-3, 7) = 4. But in SQL, -3 % 7 = -3

Am I using % wrong, or does SQL do mod

相关标签:
2条回答
  • 2020-12-11 15:57

    This will give a result between 0 and n - 1 for both positive and negative values of x:

    ((x % n) + n) % n
    
    0 讨论(0)
  • 2020-12-11 16:11

    Well, modular arithmetic is done on equivalence classes of integers, so neither Excel nor any RDBMS is "doing % wrong". If you want a representative between 0 and 6, though, you can always do

    select (-3 % 7) + 7;
    
    0 讨论(0)
提交回复
热议问题