Primero que nada- creamos una tabla temporal,
Con todos los valores de la cadena:
Código SQL:
Ver originalDECLARE @S1 VARCHAR(MAX);
SELECT @S1='407.16, 536.82, 1187.03, 923.94, 80.39, 651.46, 1547.90, 119.99, 110.66, 621.76, 62.6, 1616.24, 227.85, 878.06, 824.76, 950.04, 1125.95, 208.80, 2004.48, 3358.20, 1272.52';
IF Object_ID('tempdb..#T') IS NOT NULL DROP TABLE #T;
CREATE TABLE #T(Valor DECIMAL(12,2),
Total DECIMAL(12,2));
CREATE Clustered INDEX Idx_#T ON #T (Valor DESC, Total DESC);
DECLARE @I INT;
While @S1<>''
BEGIN
SET @I=CharIndex(',',@S1+',');
INSERT INTO #T(Valor) SELECT LEFT(@S1,@I-1);
SET @S1=Stuff(@S1,1,@I,'');
END
Ahora actualizamos la columna Total con los subtotales según el orden de Valor:
Código SQL:
Ver originalDECLARE @Valor DECIMAL(12,2),
@Total DECIMAL(12,2),
@Rc INT;
SELECT @RC=1,
@Total=0;
SELECT @Valor=MIN(Valor),
@Total=@Total+MIN(Valor)
FROM #T
WHERE Total IS NULL;
While @Valor IS NOT NULL
BEGIN
UPDATE T
SET Total=@Total
FROM (SELECT Top 1 *
FROM #T
WHERE Valor=@Valor
AND Total IS NULL) T;
SELECT @Valor=MIN(Valor),
@Total=@Total+MIN(Valor)
FROM #T
WHERE Total IS NULL;
END
Y finalmente encontramos los valores utilizando un CTE recursivo (el resumen debe ser 14007.70 y no 14007.74):
Código SQL:
Ver originalDECLARE @S2 DECIMAL(12,2);
SELECT @S2= 14007.70;
WITH T AS
(SELECT Valor,
Total,
CAST(@S2-Valor AS DECIMAL(12,2)) STotal,
CAST(Valor AS VARCHAR(MAX)) SValor
FROM #T
WHERE Total>=@S2
UNION ALL
SELECT T1.Valor,
T1.Total,
CAST(T.STotal-T1.Valor AS DECIMAL(12,2)),
CAST(T.SValor+','+CAST(T1.Valor AS VARCHAR(MAX)) AS VARCHAR(MAX))
FROM T
INNER JOIN #T T1
ON T.Valor>=T1.Valor
AND T.Total>T1.Total
AND T.STotal<=T1.Total
WHERE T.STotal-T1.Valor>=0)
SELECT *
FROM T
WHERE STotal=0;