If number1
is a value from first row and number2
is value from next row, then use ROW_NUMBER()
:
;WITH cte AS (
SELECT col,
ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rn
FROM (VALUES
(-0.75640390000),
(0.58303570000),
(-0.07794400000),
(0.00000000000),
(0.58303570000),
(-0.07794400000),
(0.42976550000),
(0.58781540000),
(0.00909080000),
(0.58781540000)
) as t(col)
), rec AS (
SELECT CAST((1+col/100) as float) as d,
1 as l
FROM cte
WHERE rn = 1
UNION ALL
SELECT d * (1+col/100),
l+1
FROM rec r
INNER JOIN cte c
ON c.rn = l+1
)
SELECT TOP 1 d
FROM rec
ORDER BY l DESC
Output:
1,01874941736518
EDIT1
Challenge with 2 million rows was accepted 🙂 I create table:
CREATE TABLE [dbo].[Testing](
[id] [int] IDENTITY(1,1) NOT NULL,
[col] [decimal](19, 11) NULL,
CONSTRAINT [PK_id_test] PRIMARY KEY CLUSTERED ([id] ASC)
)
Put this in it:
;WITH cte AS (
SELECT CAST(0.00000000002 as decimal(19,11)) as col,
1 as rn
UNION ALL
SELECT CAST(col + 0.00000000002 as decimal(19,11)),
rn+1
FROM cte
WHERE rn < 2000000
)
INSERT INTO [dbo].[Testing] ([col])
SELECT col from cte
OPTION (MAXRECURSION 0)
And then make this:
;WITH rec AS (
SELECT CAST((1+col/100) as decimal(19,11)) as d,
1 as l
FROM [dbo].[Testing]
WHERE id = 1
UNION ALL
SELECT CAST( d * (1+col/100) as decimal(19,11)),
l+1
FROM rec r
INNER JOIN [dbo].[Testing] c
ON c.id = l+1
)
SELECT top 1 d
FROM rec
ORDER BY l desc
OPTION (MAXRECURSION 0)
Output was:
1.49182491770
Query was executed in 16 sec on my local PC.
EDIT2
With the help of temp table:
CREATE TABLE #Testing (
[id] [int] IDENTITY(1,1) NOT NULL,
[col] [decimal](19, 11) NULL,
CONSTRAINT [PK_id_testing] PRIMARY KEY CLUSTERED ([id] ASC)
)
INSERT INTO #Testing ([col])
SELECT Put_Column_Name_Here
FROM Put_Table_Name_Here
;WITH rec AS (
SELECT CAST((1+col/100) as decimal(19,11)) as d,
1 as l
FROM #Testing
WHERE id = 1
UNION ALL
SELECT CAST( d * (1+col/100) as decimal(19,11)),
l+1
FROM rec r
INNER JOIN #Testing c
ON c.id = l+1
)
SELECT top 1 d
FROM rec
ORDER BY l desc
OPTION (MAXRECURSION 0)
DROP TABLE #Testing