TSQL-在变量中添加每个数字

时间:2019-04-23 08:32:40

标签: sql-server tsql

是否有一种简单的方法可以将每个数字添加到整数变量中,或者我可以按数字循环它。假设变量具有一系列数字:

|Digit_tbl| 690644694

结果:

|Digit_tbl| 48

2 个答案:

答案 0 :(得分:2)

整数除法和取模运算符可用于从整数中提取每个数字:

SELECT number, SUM(number / divisor % 10) AS digitsum
FROM (VALUES
    (690644694),
    (2147483647)
) AS t(number)
INNER JOIN (VALUES
    (1),
    (10),
    (100),
    (1000),
    (10000),
    (100000),
    (1000000),
    (10000000),
    (100000000),
    (1000000000)
) AS x(divisor) ON divisor <= number
GROUP BY number

答案 1 :(得分:2)

一种方法是使用递归cte:

declare @num int = 690644694;


with cte as (
    select @num as num, @num % 10 as digit 
    union all
    select num / 10, num / 10 % 10
    from cte
    where num > 0
)

SELECT SUM(digit)
FROM cte

结果:48

另一种可能应该具有更好的性能(不是可以对单个int进行测量)的选项是使用十进制cte的幂:

declare @num int = 690644694;

With Tally as
(
    SELECT TOP 10 POWER(10, (ROW_NUMBER() OVER(ORDER BY @@SPID))-1) As n
    FROM sys.objects
)

SELECT SUM(@num / n % 10)
FROM Tally
WHERE n <= @num

(SQL Server中int的最大值为10位-因此,提示计数中的top 10-值为1,10,100,.... 1000000000)