Skip to content
Advertisement

How to Bring in Full 24 Month Span (including NULL values) in MySQL Query Count

Attempting to create a ‘Previous Year’ vs ‘Current Year’ Graph using a jQuery plug-in with data from my MySQL database.

The data for such is like this

if we pretend the xmonthsago is an integer value.

The case I am working for is a database for an Inventory System and I am looking to create a 24-month span for sold counts on certain SKUs using my inventory_history table.

I have used this current query with success:

Which, for example, outputs:

I am wondering if it is possible to streamline this query even more to give me a proper output which includes all months in between that do not have any COUNTs

Output something like this:

Anyone have any idea on how I may accomplish this with a MySQL query?

Advertisement

Answer

If you have data in the table for all months, the simplest method is probably conditional aggregation:

Notes:

  • There is no reason to use date_format() when MySQL has convenient built-in functions.
  • Only use single quotes for string and date constants, not for column aliases especially.
  • You don’t need to escape your column aliases.
  • The GROUP BY columns should match the unaggregated columns in the SELECT. They can use aliases.
  • The SUM() uses a very convenient feature of MySQL. It treats booleans as integers, with 1 for true and 0 for false.
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement