I have a table containing a user id, purchase amount, and date. I need to calculate the sum over several periods, for the same user. For example, given:
| UserId | Date | Amount |
|---|---|---|
| 1 | 2021-01-03 | 10 |
| 1 | 2021-01-10 | 20 |
| 1 | 2021-02-07 | 30 |
From an API, for the same user, I might need to sum and return all of the following ranges:
| Description | Range | Expected Result |
|---|---|---|
| The first week of Jan | 1st (Friday) to the 3rd (Sunday) | 10 |
| The month of Jan | 1st to the 31st | 30 |
| The month of Feb | 1st to the 28th | 30 |
Some restrictions:
- I don't know the dates up front (the consumer either needs calendar periods, or rolling periods), so I don't think I can create curated queries using
SUMandCASE? I saw an example of this here. - I also need to use a stored procedure when interacting with the DB, so I wouldn't be able to dynamically create the
SELECTstatement from the API.
I don't have a lot of experiences writing SQL, but I imagine it's better to have a single query that calculates all of the totals than calculating the sums individually? Any suggestions?