Skip to content
Advertisement

How to show the results as zero when there is no record

I have the 3 tables below with the following data

I need to write a query that calculates country-wise sales for all of the models along with the revenue generated for the year 2017. The result should be in the following format: country_name | model_name | revenue

I’m trying this query below. I need to bring the country/models that do not have any sales too with a revenue of 0, but my query only return the country/models that have any sales.

Result of the query

What i really need (the order is not important)

There is a simple way to do that?

Advertisement

Answer

You can cross join the countries and model table to generate all possible combinations, and then bring in the sales with a left join:

Note that I did the following changes in the query:

  • use half-open intervals for the date comparison; this will be more efficient, since no date function needs to be applied on sales_date

  • add all non-aggregated columns to the group by clause, making the query compliant with MySQL mode ONLY_FULL_GROUP_BY, which is enabled by default starting MySQ 5.7

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