如何计算MySQL中Text值的每个数字的总和?
例如
SET @Chars = CONCAT('1','2','33');
-- @Chars = '1233'
-- and result should be 1+2+3+3 = 9.
答案 0 :(得分:1)
是的,不是很好,但这是一种方法。我喜欢你 - 不得不做一些现场检查。我们检查数字计算,我需要一些特定的帐户,其中数字将以各种方式求和。
select (substring('123456', 1, 1) +
substring('123456', 2, 1) +
substring('123456', 3, 1) +
substring('123456', 4, 1) +
substring('123456', 5, 1) +
substring('123456', 6, 1) +
substring('123456', 7, 1) +
substring('123456', 8, 1) +
substring('123456', 9, 1) +
substring('123456', 10, 1) +
substring('123456', 11, 1) +
substring('123456', 12, 1)) as sumOfDigits;
所以只需用你的字符串替换'123456',然后确保本例中的1..12足以覆盖你期望计算总数的最大字符串的长度。
这是我的真实世界的例子:
select (substring(a.member_number, 1, 1) +
substring(a.member_number, 2, 1) +
substring(a.member_number, 3, 1) +
substring(a.member_number, 4, 1) +
substring(a.member_number, 5, 1) +
substring(a.member_number, 6, 1) +
substring(a.member_number, 7, 1) +
substring(a.member_number, 8, 1) +
substring(a.member_number, 9, 1) +
substring(a.member_number, 10, 1) +
substring(a.member_number, 11, 1) +
substring(a.member_number, 12, 1)) as sumOfDigits,
a.member_number from account a
left join account a2 on a2.member_number = a.member_number and a2.discriminator = 'D'
where a.discriminator = 'S'
and a2.account_id is null having sumOfDigits = 16;
答案 1 :(得分:0)
根据https://en.wikipedia.org/wiki/Digital_root,有一个非常简单的公式可以做到。
在MySQL中可以这样指定:
@Chars - 9 * FLOOR( (@Chars-1 ) / 9 ).
或者可以使用任何字段/表达式代替@Chars。