0

I have a query that returns DateTime Spans an employee has worked for a day, what week of the year that time relates to and the date of the spans. It works really well, but I want to calculate a running total by day for each day in a particular week.

Currently, my query looks like this:

SELECT A.*
FROM (
    SELECT WeekNumber, SUM(NumberOfSecondsWorked) AS NumberOfSecondsWorkedInDay, MIN(FromTime) AS StartOfDay, MAX(ToTime) AS EndOfDay, (SELECT WeeklyTotal = SUM(NumberOfSecondsWorked) FROM #temp AS T2 WHERE T2.WeekNumber = T1.WeekNumber) AS WeeklyTotal
    FROM #temp AS T1 GROUP BY DayMonth, WeekNumber) A

And returns this:

enter image description here

The issue I'm having is I would like the Weekly total to be summed by Row for each week, so the data would look like the following:

enter image description here

Where the weekly total sums up for each row. Can anyone tell me what I'm doing wrong in my query?

user1501171
  • 210
  • 1
  • 3
  • 17
  • 1
    Possible duplicate of [Calculate running total / running balance](https://stackoverflow.com/questions/11310877/calculate-running-total-running-balance) – Han Jul 05 '19 at 17:06

2 Answers2

3

Your query and your result set are not really consistent. Your result set has StartOfDay for instance.

But, you seem to want:

SELECT WeekNumber, SUM(NumberOfSecondsWorked) AS NumberOfSecondsWorkedInDay,
       MIN(FromTime) AS StartOfDay, MAX(ToTime) AS EndOfDay,
       SUM(SUM(NumberOfSecondsWorked)) OVER (PARTITION BY WeekNumber ORDER BY MIN(FromTime))
FROM #temp AS T1
GROUP BY DayMonth, WeekNumber;

EDIT:

In SQL Server 2008, you need a different approach such as a correlated subquery:

WITH wn as (
      SELECT WeekNumber, SUM(NumberOfSecondsWorked) AS NumberOfSecondsWorkedInDay,
             MIN(FromTime) AS StartOfDay, MAX(ToTime) AS EndOfDay
      FROM #temp T1
      GROUP BY DayMonth, WeekNumber
     )
SELECT wn.*,
       (SELECT SUM(wn2.NumberOfSecondsWorked)
        FROM wn wn2
        WHERE wn2.WeekNumber = wn.WeekNumber AND
              wn2.FromTime <= wn.FromTime
       )
FROM wn;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1

try like below by using window function

     SELECT WeekNumber,
     SUM(NumberOfSecondsWorked) AS NumberOfSecondsWorkedInDay,
     MIN(FromTime) AS StartOfDay, MAX(ToTime) AS EndOfDay,
     SUM(NumberOfSecondsWorked) over( order by WeekNumber) AS WeeklyTotal
    FROM #temp AS T1
    GROUP BY DayMonth, WeekNumber
Zaynul Abadin Tuhin
  • 31,407
  • 5
  • 33
  • 63