首页 > 解决方案 > 将数字拆分并添加到分配的权重 n SQL 的逻辑

问题描述

我有以下要求。下面是程序。我没有得到预期的结果。请纠正我哪里出错了。

0   0   0   0   0   0   1   1   1   5   0   8   0   0   2   0   0   4   0   0   4   0   0   1   0   0   0   0   4   0   0   0   0   0   0   0   0   0   4   3   1   2   4   0   1   1   0   1   1   0   0   0   0   0   0   1   1   1   0                                                                               

从左到右分配权重 7、5、3、2:

7   5   3   2   7   5   3   2   7   5   3   2   7   5   3   2   7   5   3   2   6   5   3   2   7   5   3   2   5   5   3   2   7   5   3   2   7   5   3   2   7   5   3   2   7   5   3   2   7   5   3   2   7   5   3   2   7   5   3                                                                               

将每个数字乘以其分配的权重:

0   0   0   0   0   0   3   3   7   25  0   16  0   0   6   0   0   20  0   0   24  0   0   2   0   0   0   0   20  0   0   0   0   0   0   0   0   0   12  6   7   10  12  0   7   5   0   2   7   0   0   0   0   0   0   2   7   5   0                                                                               

拆分和添加数字:

0   0   0   0   0   0   3   3   7   7   0   7   0   0   6   0   0   2   0   0   6   0   0   2   0   0   0   0   2   0   0   0   0   0   0   0   0   0   3   6   7   1   3   0   7   7   7   2   7   0   0   0   0   0   0   2   2   5   0   

总数为 104

将总和除以模数 10:

104/10 = 10.4

从模 10 中减去余数:

10-4 = 6

检查数字:

6

标签: sql-server

解决方案


我没有通过您的查询,因为它可以通过基于集合的解决方案来完成。不需要光标。只需使用递归生成一个数字表。如果您有数字表,请使用它

declare @str varchar(100) = '00000011150800200400400100004000000000431240110110000001110'

; with 
number as   -- replace with a number or tally table if you have one
(
    select  n = 1
    union all
    select  n = n + 1
    from    number
    where   n   < len(@str)
),
weights as
(
    select  n = 1, weights = 7  union all
    select  n = 2, weights = 5  union all
    select  n = 3, weights = 3  union all
    select  n = 0, weights = 2
)
select  check_digit = 10 
                    - ( sum(s.d1 + s.d2) % 10 )
from    number n
        inner join weights w    on  n.n % 4 = w.n
        cross apply
        (
            select  d1 = convert(int, substring(@str, n.n, 1)) * w.weights / 10,
                    d2 = convert(int, substring(@str, n.n, 1)) * w.weights % 10
        ) s

您可以使用以下select子句验证间歇性结果

select  n.n, 
        digit = convert(int, substring(@str, n.n, 1)), 
        [weight] = w.weights,
        [digit x weight] = convert(int, substring(@str, n.n, 1)) * w.weights,
        s.d1, s.d2

推荐阅读