Skip to content
Advertisement

What is wrong with this running total (cumulative column) in Oracle select with a window function?

I have a query containing 0 or 1 in a column. For demonstration purposes I replaced the 1 with 77 so its more easy to see:

The result is simply a consecutive date column and a marker if this date is a workday or not. (in real life I do a holiday calculation as well, but that’s not the problem):

I want to add a running total over is_workday, meaning a cumulative value. I am sure Oracles window functions are made for this.

But I must miss something here, because I do not get a running total, but just the value itself.

Obviously it should be:

I thought it would wirk like this:

  • sum(x.is_workday) — do the sum over the 77-values
  • partition by x.the_date — make windows/sections/parts with one row each (in my case)
  • order by x.the_date asc — order those rows by date
  • rows between unbounded preceding — sum between very first row…
  • and current row — … and the current row.

What am I missing here?

Advertisement

Answer

Remove the PARTITION BY clause of your query as the scope you want for the window is the entire query and not each individual date:

You can also use date literals, need to remove the AS in the table alias (and don’t actually need any table aliases) and can use the difference between date and the start of its ISO week (d - TRUNC( d, 'IW' )) as a method of finding Saturday and Sunday that is independent of the NLS_TERRITORY session parameter.

You could also remove the ROWS BETWEEN clause as ROWS BETWEEN unbounded preceding AND current row is the default behaviour. However, if that is the behaviour you require then you may just as well leave it in to demonstrate that that window is your expected result.

Output:

THE_DATE  | IS_WORKDAY | WORKDAYS_CUMUL
:-------- | ---------: | -------------:
01-JAN-19 |          1 |              1
02-JAN-19 |          1 |              2
03-JAN-19 |          1 |              3
04-JAN-19 |          1 |              4
05-JAN-19 |          0 |              4
06-JAN-19 |          0 |              4
07-JAN-19 |          1 |              5
08-JAN-19 |          1 |              6
09-JAN-19 |          1 |              7
...
24-DEC-20 |          1 |            518
25-DEC-20 |          1 |            519
26-DEC-20 |          0 |            519
27-DEC-20 |          0 |            519
28-DEC-20 |          1 |            520
29-DEC-20 |          1 |            521
30-DEC-20 |          1 |            522

db<>fiddle here

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement