【问题标题】:SQL Sum of each character in a numberSQL 数字中每个字符的总和
【发布时间】:2014-06-10 15:07:42
【问题描述】:

我想在 SQL 中对整数的每个字符求和

例如。我有16273481 as INT

但是现在(不用复杂的方法)总和

1 + 6 + 2 + 7 + 3 + 4 + 8 + 1 = 32

【问题讨论】:

标签: sql function math add


【解决方案1】:
DECLARE @someInt INT = 16273481


-- you could put this all into a function
-- and then it would be reusable...
-- 
-- like... SELECT SumOfIndividualIntegers(16273481)

DECLARE @count INT = LEN(@someInt),
        @counter INT = 1

DECLARE @Sum INT = 0

WHILE @counter <= @count
BEGIN
    SELECT @sum += CAST(SUBSTRING(CAST(@someInt AS VARCHAR), @counter, 1) AS int)
    SELECT @counter += 1
END

SELECT @sum --32
-- and then you would RETURN @sum instead

【讨论】:

  • 谢谢,我认为会有一种更简单的方法,例如拆分,或者将子字符串转换为 int sum,在这些行中,但这似乎是最好和最干净的方法。
【解决方案2】:

使用余数运算符是否适合您的循环情况?

伪代码:

x = 16273481; 总和 = 0;

循环: 总和 = 总和 + (x % 10); x = (x / 10);

类似的东西?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-11
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    相关资源
    最近更新 更多