我需要将一个数量(Number)分解为组件,例如,58963的数量将分为50000,8000,900,60和3,如何在sql中使用函数实现这一点,任何想法?
此致
伊尔凡
答案 0 :(得分:2)
尝试
DECLARE @amount INT = 58963
DECLARE @temp INT
DECLARE @i INT = 0
DECLARE @tempStore TABLE(val int)
WHILE(@amount>0)
BEGIN
SET @temp = @amount % 10;
SET @amount = @amount /10;
INSERT INTO @tempStore VALUES(@temp * POWER(10, @i))
SET @i = @i+1;
END
SELECT * FROM @tempStore ORDER BY val DESC
如果值不适合整数范围,则可以使用bigint
代替int
。
如果要获得逗号分隔输出,请尝试
DECLARE @amount BIGINT = 589625
DECLARE @temp BIGINT
DECLARE @i INT = 0
DECLARE @tempStore TABLE(val BIGINT)
WHILE(@amount>0)
BEGIN
SET @temp = @amount % 10;
SET @amount = @amount /10;
INSERT INTO @tempStore VALUES(@temp * POWER(10, @i))
SET @i = @i+1;
END
DECLARE @tmp VARCHAR(MAX)= ''
select @tmp = @tmp + CONVERT(VARCHAR(100), val ) + ', ' from @tempStore ORDER BY val DESC
select SUBSTRING(@tmp, 0, LEN(@tmp))
如果你想用数据库方式而不是通用编程逻辑(不想要WHILE循环)来实现它,那么你可以尝试
DECLARE @amount AS INT = 58963;
;WITH cte
AS ( SELECT 1 AS n, @amount AS m, 1 as p, 1 as r
UNION ALL
SELECT (cte.m%10), (cte.m / 10), (cte.p*10), ((cte.m%10) * (cte.p*10))/10
FROM cte
WHERE cte.m > 0
)
SELECT cte.r --,*
FROM cte WHERE (cte.n*cte.p)/10 > 0
--ORDER BY cte.r DESC
答案 1 :(得分:1)
对于SQL Server
DECLARE @num INT = 58963;
with decList as
(
select 10 AS decNum
union all
select decNum * 10 AS dt
from decList
where decNum <= @num
)
select CASE WHEN decNum > 10
THEN ((@num % decNum) / (decNum / 10)) * (decNum / 10)
ELSE @num % decNum
END
from decList
答案 2 :(得分:0)
这适用于任何数字。
DECLARE @amount AS INT = 58963;
WITH cte
AS ( SELECT 1 AS n
UNION ALL
SELECT cte.n * 10
FROM cte
WHERE cte.n < @amount / 10
)
SELECT ( ( @amount % ( cte.n * 10 ) ) / cte.n ) * cte.n
FROM cte;