所有数字的总和归结为一位数

时间:2018-05-23 09:57:57

标签: tsql

我有一张

下的表格
numbers
794
709090

我需要的是所有数字的总和,例如 7 + 9 + 4 = 20; 2 + 0 = 2 7 + 0 + 9 + 0 + 9 + 0 = 25; 2 + 5 = 7

我尝试使用以下脚本,但不知何故不起作用:

declare @t table(numbers int)
insert into @t select 794 union all select 709090

declare @maxValue int
select @maxValue = max(numbers) from @t

;with cte as(
SELECT SUM(CAST(SUBSTRING(cast(numbers as varchar(1000)),number,1) AS INT)) SUMOFDIGITS FROM @t 

cross apply ( 
SELECT DISTINCT number FROM
MASTER..SPT_VALUES WHERE number > 0 AND number <= DATALENGTH(@maxValue) ) x)

select SUMOFDIGITS, finalsum = cast(left(SUMOFDIGITS,1) as int)+cast(right(SUMOFDIGITS,1) as int)
from cte

1 个答案:

答案 0 :(得分:3)

DECLARE @a int = 709090
select   (@a - 1) % 9 + 1