sql-server - 将数字拆分并添加到分配的权重 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
解决方案
我没有通过您的查询,因为它可以通过基于集合的解决方案来完成。不需要光标。只需使用递归生成一个数字表。如果您有数字表,请使用它
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
推荐阅读
- vb.net - 如何更改比较多个文本框
- tabs - 在 Materialise 1.0.0 中切换选项卡的问题
- python - 如何遍历每 10 秒刷新一次的 Web 元素列表?
- java - 在 Apache JsonToStringStyle 中格式化日期
- python - 为什么“浏览”方法使用不存在的 id 返回错误的记录集?
- javascript - react-native 的水平滑块插件
- json - 如何从文件中获取所有 JSON 名称并将其存储到字符串中
- css - 为什么相同厚度和相同位置的边框不完全重叠?
- vegan - 为什么在运行 adonis 函数(permanova)时,df 总是得到 1?
- sharepoint - 如何为 Sharepoint Online 2018 中的文档创建匿名链接