Skip to content
Advertisement

mysql, Data for the last 3 months, including zeros

Consider the following schema:

I need to come up with single SQL query, that will produce something like this

Date must include 3 last months and should be dynamic (when query is executed in Jan 2020, it includes Jan 2020, Dec 2019 and Nov 2019; if in Aug 2020, it should include June, July and August 2020). In general, query should a report about sum of all expenses per investment within last 3 months, including months without any expenses.

Description of tables being involved: Investments – stores information about investments, like houses, apartments being built; Schedules – Each investment follows specific schedule Schedule_Items – Schedule elements Expenses – stores information about expenses Schedule_expenses – relation table between expenses and schedule items

What I did so far: I created a view called ‘calendar_3_months’ that contains dynamic values, always 3 last months, formatted like: “%Y-%m”. I came up with a query that produces almost expected result (incorrect ‘total’ values). I tried different joints but they are not giving me a desired outcome. The best I came up with was:

http://sqlfiddle.com/#!9/5e2f3f/1

Please let me know the direction of changes to get this done?

Advertisement

Answer

If your problem is the missing 0 row, then this includes it:

Here is a SQL Fiddle.

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