Skip to content
Advertisement

Need Help Generating NULL Entries for Months with No Orders

I have to create output that shows all fields from a table (Tbl) and create an additional column that calculates Cumulative Sum for each customer by month, (eg if a customer has two sales in April, the new column will have the Sum of those sales and any prior sales on both rows). That much I can do.

My issue is generating rows every month for every client even when they have no sales, and still having the cumulative column show the previous month’s cumulative sum correctly.

Desired output: Picture Link

I’ll list the code below, but this is a link to a SQL fiddle with sample data and the two queries of the pieces that i have working (with help from you wonderful people on this site). http://sqlfiddle.com/#!15/1d86b/11

I can generate the desired Cumulative running sum by customer and month using the first query.

I can also generate a base table that gives me a month_id for every customer for every month in the second query.

I need help making the combination of those two that will generate the desired output with the null rows for when months/Customers don’t have any sales.

Any ideas? Thanks!

Advertisement

Answer

Based on your description, you can combine window functions with generate_series():

Here is a SQL Fiddle.

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