Skip to content
Advertisement

Calculate Cumulative Sum-Running Total/Sale for Each Day of the Month in Redshift

Problem Statement: Get running sales for every calendar date for every product.

Brief Background: Entries are added to the sales table when sales is made. If a particular product has not made any sales for a particular date, no record will be inserted.

Sales Table Structure.

SQL to generate the above view.

Expected Output: For every single calendar day of the month (In this case JAN 2020) get rolling sales for last n days(this number can be anything,and will be harcoded in final query).

Steps Taken: I have tried existing calendar table(snippet to create calendar table shared below) for this purpose and sum window function.However, as rolling sum needs to be calculated for each product code using partition by product code sums up at product level not day level. I understand this is the expected behaviour. My ask here is what should be the approach when using redshift to solve this problem statement. Also, is it a problem statement that can be solved using window function.

SQL to create calendar table:

SQL used as of now for final Output:

Advertisement

Answer

You will have to use window function for cumulative sum. The query below creates dummy 0 valued sales for each product and for each calendar day. This will ensure the output has cumulative sales value row for each product and each calendar day.

Here is a SQL Fiddle.

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