Skip to content
Advertisement

Count the total number of records before a specific day for the last N days in SQL

I have a table that stores customer information including their registration date with the service. I would like to know the total number of subscribed customers (from the beginning of the service up until that day) at the end of the day for the past 10 days.

I imagine the solution would be something similar to a for loop, so the best I managed so far is the following:

The problem with the above script is that it produces 10 different tables and I haven’t been able to union them together. I’m fairly new to SQL so there might be a simpler solution that I’m missing!

The output I have in mind looks like this:

date total number registered
2022-01-30 500,000
2022-01-29 499,800

Advertisement

Answer

It has nothing to do with a loop. You would simply create an SQL select that selects them. ie:

EDIT: Question is edited to show the desired output now, then it would need a different way like:

EDIT: If as P.Salmon said you were after a “running total” then you still can get it with a slight modification to code:

Here is DBFiddle demo

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