priyanka.sarkar
priyanka.sarkar

Reputation: 26498

Sum of all digits boiled down into a single digit

I have a table as under

numbers
794
709090

what I need is a sum of all the digits such as 7+9+4 = 20; 2+0=2 or 7+0+9+0+9+0=25; 2+5=7.

I tried with the below script but somehow not working:

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

Upvotes: 1

Views: 189

Answers (1)

Stanislav Kundii
Stanislav Kundii

Reputation: 2894

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

Upvotes: 2

Related Questions