Skip to content
Advertisement

Find Previous Month MTD (Month to Date) Calculation in BigQuery

Assuming I have initial table of date and each order value of the date:

So I use this query for calculating current MTD (cumulative gross order in a month from day 1 of certain month to certain date in that month),

the result will be something like this:

The idea is to also have value of previous month MTD value for all row in the date range, so in the 25 and 27 Nov, previous MTD value will be 0 because there are no prior gross order value. And in the 30 december row, the value will be sum of gross_order between 1 to 30 november, which give us 50 + 350 = 400

Expected result:

I’m kinda stuck as how to calculate the previous mtd value, is there any way to do it? Thank you

Advertisement

Answer

Now that I understand the question, you can use a correlated subquery:

The subquery is matching rows from the previous month (the first condition) and then comparing the date (the second condition).

This works on the data you have supplied.

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