In the first place, and in case you do not have it clear, it is convenient to use the difference in seconds between both dates ( resta
), for example: select datediff(s, <fechadesde>, <fechahasta>)
. So our problem will be based on accumulating the seconds. There is a lot of information in the network about this particular point, just look for "cumulative sum in sql server" and you will see that there is enough written.
Since the cumulative sum will depend on an order, it is convenient to have a ID
for each record in order to determine the order and we will see that it is necessary for the proposed solution, in this example we assume that you already have it or you have created it, on the other hand we are going to use the same values of resta
of your example:
DECLARE @Ejemplo TABLE (
id INT IDENTITY,
clave CHAR(1),
resta INT
)
INSERT INTO @Ejemplo (clave, resta)
VALUES ('a', 8), ('a', 4), ('b', 8), ('b', NULL), ('c', 2), ('c', 4), ('c', 5)
With this we will have a table @Ejemplo
with the data of your question. An option to accumulate the sum that is quite compatible between versions of SQL Server, is as follows:
SELECT t1.clave,
t1.resta,
SUM(t2.resta) AS 'Total'
FROM @Ejemplo t1
INNER JOIN @Ejemplo t2
ON t1.id >= t2.id
AND t1.clave = t2.clave
GROUP BY t1.id, t1.clave, t1.resta
ORDER BY t1.id
Here we see the use of id
, we use it to add the previous and current values of each row. The output obtained:
clave resta Total
===== ===== =====
a 8,00 8,00
a 4,00 12,00
b 8,00 8,00
b NULL 8,00
c 2,00 2,00
c 4,00 6,00
c 5,00 11,00
Another solution is to use OVER PARTITION
but this applies from SQL 2008
SELECT t.clave,
t.resta,
SUM(t.resta) OVER (PARTITION BY clave order by id) as 'Total'
FROM ( SELECT ROW_NUMBER() OVER (ORDER BY clave) AS 'id',
clave,
resta
FROM @Ejemplo
) T
In passing we ignore the need for id
using the ROW_NUMBER()
but in any case I do not recommend it, it is preferable to have a field that effectively serves to sort the results, so that the query always returns the same order. I understand that you know then how to transform the seconds in the format you request, but I recommend you this answer very current.