In SQL Server 2012, you can do this using the cumulative sum window function. You can also get the timeslot in a way that comes close to working in more than one database:
select timeslot,
sum(amount) as amount,
sum(sum(amount)) over (order by timeslot) as cumamount
from (select t.*,
(cast('2014-03-04 00:00:00' as datetime) +
cast( ("timestamp" - cast('2014-03-04 00:00:00' as datetime))*24*4 as int)/(24.0*4)
) as timeslot
from table t
) t
where Timestamp between '2014-03-04 00:00:00' and '2014-03-04 23:59:59'
group by timeslot;
The idea behind the timeslot
calculation is to take the difference between timestamp
and midnight of some day. This gives the number of days (with fractions) between the two dates. Then multiply this by 24 for hours and 4 for the 15-minute intervals, and it gives the number of 15 minute intervals since midnight on some date. Truncate this value by converting to an integer and add back to the original date. This is all done in a subquery, so the calculation can be repeated.
This approach will work in many databases, though there might be some nuances on the exact expression. The formatting of the datetime
would be rather database specific.
The rest is just using the cumulative sum function. If you don't have this, then you can use a correlated subquery instead.