Skip to content
Advertisement

window function rolling sum

I have a window function that gives me a rolling sum as below:

    SELECT start_terminal,
       duration_seconds,
       start_time,
       sum(duration_seconds) OVER
         (PARTITION BY start_terminal order by start_time)
         AS running_total
  FROM tutorial.dc_bikeshare_q1_2012
 WHERE start_time < '2012-01-08'

but when some timestamps in the start_time column are equal the rolling sum stays the same, which makes sense bc I am ordering by start time, but it does not properly add the duration_seconds in the rolling sum as below: how can i fix or account for this?

current output:
     start_terminal duration_seconds start_time         running_total
        31000          74              2012-01-01 15:32:00     74
        31000          291             2012-01-02 12:40:00     365
        31000          520             2012-01-02 19:15:00     885
        31000          424             2012-01-03 07:22:00     1756
        31000          447             2012-01-03 07:22:00     1756
        31000         1422             2012-01-03 12:32:00     3178
         31000         348             2012-01-04 17:36:00     3526

desired:

start_terminal duration_seconds start_time         running_total
            31000          74              2012-01-01 15:32:00     74
            31000          291             2012-01-02 12:40:00     365
            31000          520             2012-01-02 19:15:00     885
            31000          424             2012-01-03 07:22:00     1756
            31000          447             2012-01-03 07:22:00     2203
            31000         1422             2012-01-03 12:32:00     3625
             31000         348             2012-01-04 17:36:00     3973

Advertisement

Answer

If you add the duration_seconds column to the order by in the partition, that should give you what you’re looking for.

    SELECT start_terminal,
       duration_seconds,
       start_time,
       sum(duration_seconds) OVER
         (PARTITION BY start_terminal order by start_time, duration_seconds)
         AS running_total
  FROM tutorial.dc_bikeshare_q1_2012
 WHERE start_time < '2012-01-08'
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement