I have sales table with fields Datatime(DateTime
) and sales(Number
).
How do I write a SQL query to fetch data grouped by month year for last 6 months with a new column 'running count'.
Running count is a positive whole number which starts with 1 (if sales else 0) then 2 if there is a sale for next month (given there is a sale and running count was 1 for the previous month) and so on. If there is no sales for a month running count will be 0 for that month and if there is a sale for next month it restarts with 1 and so on.
Example:
Current month year is '09/2017' and there are sales for March, April, June, July, August but no sales (no row) for the month of May.
So the output will be:
| Month_Year | Sum(Sales) | Running_Count |
| 03/2017 | 1000 | 1 |
| 04/2017 | 1500 | 2 |
| 05/2017 | 0 | 0 |
| 06/2017 | 300 | 1 |
| 07/2017 | 550 | 2 |
| 08/2017 | 1900 | 3 |
Suggestions are welcomed to edit this question.