SQL分解一个int并乘以每个数字

时间:2018-08-08 21:36:25

标签: sql

如果我将以下内容作为整数1234并将其分解为1,2,3,4,我该怎么做,以便将它们分开并能够将它们相乘,例如1×3、2× 5、3×3、4×5具有3,5的图案,而不考虑它们是偶数还是奇数。

1 个答案:

答案 0 :(得分:0)

这是sql-server版本,但应该可以在其他几个版本中使用。想法是,您先获取一个Tally表,一个序号表,然后将其与整数的数字相接,然后进行计算/分解。

http://rextester.com/JTUXP51597

;WITH cteBase AS (
    SELECT * FROM (VALUES (0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) t(n)
)

, cteTally AS (
    SELECT
       ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) as N
    FROM
       cteBase c10
       CROSS JOIN cteBase c100
)

, cteValue AS (
    SELECT * FROM (VALUES (1234)) t(value)
)

SELECT
    v.value
    ,CAST(SUBSTRING(CAST(v.value AS VARCHAR(100)), t.N, 1) AS INT) as Digit
    ,CASE t.N % 2 WHEN 0 THEN 5 ELSE 3 END as Multiplier
    ,SUBSTRING(CAST(v.value AS VARCHAR(100)), t.N, 1) + ' x ' + CASE t.N % 2 WHEN 0 THEN '5' ELSE '3' END as Equation
    ,CAST(SUBSTRING(CAST(v.value AS VARCHAR(100)), t.N, 1) AS INT) * CASE t.N % 2 WHEN 0 THEN 5 ELSE 3 END as Result
FROM
    cteValue v
    INNER JOIN cteTally t
    ON LEN(CAST(v.value AS VARCHAR(100))) >= t.N