Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of digits of a number in sql server without using traditional loops like while

Tags:

sql

sql-server

var1 = 12345
output = 1+2+3+4+5 = 15

I tried the following

Declare @var1 int   = 12345,
        @Length int = len(12345)

;with SUMM as 
(
SELECT SUBSTRING(CAST(@var1 AS VARCHAR) ,1,@Length)%10 N
UNION ALL
SELECT SUBSTRING(CAST(@var1 AS VARCHAR) ,1,@Length-1))%10 N
FROM SUMM
WHERE @Length <= len(@var1)
)
SELECT SUM(N) FROM SUMM;

Please help me with achieving it with cte and any other methods other than traditional looping are welcome

like image 428
TharunRaja Avatar asked Feb 09 '23 09:02

TharunRaja


2 Answers

It's a fun exercise if a bit pointless.

DECLARE @var1 int   = 12345;

WITH i AS (
    SELECT @var1 / 10 n, @var1 % 10 d

    UNION ALL

    SELECT n / 10, n % 10
    FROM i
    WHERE n > 0
)
SELECT SUM(d)
FROM i;
like image 150
Matt Hamilton Avatar answered Feb 11 '23 07:02

Matt Hamilton


SELECT 
SUM(CAST (SUBSTRING(STRING.B, V.NUMBER+1, 1)AS INT) )
FROM 
(SELECT '12345' B) STRING
JOIN MASTER..SPT_VALUES V ON V.NUMBER < LEN(STRING.B)
WHERE V.TYPE = 'P'
like image 22
TharunRaja Avatar answered Feb 11 '23 05:02

TharunRaja