I'm looking for a solution where I can use a cumulative sum in combination with a group by.
I have the following table:
| office_id | time | revenue |
|---|---|---|
| 1 | 2022-01-01 12:00:00 | 100 |
| 1 | 2022-01-02 13:10:00 | 50 |
| 1 | 2022-01-02 17:00:00 | 40 |
Using the following query, I can get the cumulative sum for each entry:
SELECT office_id, date_trunc('day', time) as ts, sum(revenue) over (partition by office_id order by time) as cum_rev FROM business.revenue ORDER BY office_id, ts; Which gives me:
| office_id | ts | cum_rev |
|---|---|---|
| 1 | "2022-01-01 00:00:00" | 100 |
| 1 | "2022-01-02 00:00:00" | 150 |
| 1 | "2022-01-02 00:00:00" | 190 |
What I want to obtain is to group the data on the truncated time, ie:
| office_id | ts | cum_rev |
|---|---|---|
| 1 | "2022-01-01 00:00:00" | 100 |
| 1 | "2022-01-02 00:00:00" | 190 |
What changes to my query do I have to make to get this result? I have a feeling I should group by my ts field but it's not that easy unfortunately.
office_idchange from 1,2,3 to 1,1,1? You won't get a running total if you partition by office_id and you have three different ones.