2014/06/22

SUMATORIAS ACUMULADAS

A partir de la versión 2012 es posible generar sumatorias acumuladas sin necesidad de utilizar un subquery, les mostraré como: Primero crearemos una tabla de pruebas:
IF OBJECT_ID( 'datosPrueba') IS NOT NULL
       DROP TABLE datosPrueba

CREATE TABLE datosPrueba ( cve INT IDENTITY(1,1) , valor INT )
GO

INSERT INTO datosPrueba( valor )
VALUES( 2 ) , ( 3 ) , ( 4 ) , ( 5 ) , ( 10 ) , ( 20 ) , ( 34 ) , ( 50 )

SELECT * FROM datosPrueba

Ahora, simplemente aplicamos un OVER después de la función de agregado.
SELECT *  , SUM( valor ) OVER( ORDER BY cve ) as total
FROM datosPrueba

También podemos utilizar la clausula PARTITION BY para separarlos por grupos.
IF OBJECT_ID( 'datosPrueba') IS NOT NULL
       DROP TABLE datosPrueba

CREATE TABLE datosPrueba ( cve INT IDENTITY(1,1) , letra CHAR(1), valor INT )
GO

INSERT INTO datosPrueba( letra, valor )
VALUES( 'a' , 2 ) , ( 'a', 3 ) , ( 'a', 4 ) , ( 'b', 5 ) , ( 'b', 10 ) , ( 'b', 20 ) , ( 'c', 34 ) , ( 'c', 50 )

SELECT *  , SUM( valor ) OVER( PARTITION BY letra ORDER BY cve ) as total
FROM datosPrueba

SALUDOS!
COMPARTE ESTA INFORMACION SI TE PARECIO INTERESANTE

0 comentarios:

Publicar un comentario