1

I have the following schema in MySQL (read only permissions database)

http://sqlfiddle.com/#!9/1eafc/1

As you can see there are only 5 country codes:

GB, USA, GR, ES, DE

Some months some of the records might not contain one of the countries because no record was created for this country that month.

As you can see in the sqlfiddle, GB records were only created in September.

Is there any way if there isn't any record for a country in that month, instead of not being returned, to show 0 or NULL or something?

I've tried so far different variations of ISNULL, IFNULL and COALESCE but none of them worked.

I want to return something like the following

UK 0
USA 13
GR 5
ES 12
DE 1

Any ideas?

Sonamor
  • 231
  • 3
  • 17
  • Fiddle not loading... – JohnHC Sep 29 '16 at 09:12
  • try to use that if($count=="" || $count==0){echo" ";} – mhmd Sep 29 '16 at 09:13
  • 1
    You probably want to `SELECT ... FROM country_codes LEFT JOIN records ON ... WHERE ...`, this will include even the countries, that have 0 records. Just guessing, since Your SQL fiddle won't load :-( – Roman Hocke Sep 29 '16 at 09:15
  • See e.g. [MySQL how to fill missing dates in range?](http://stackoverflow.com/questions/3538858/mysql-how-to-fill-missing-dates-in-range), [Mysql - filling rows for missing months](http://stackoverflow.com/questions/25358457/mysql-filling-rows-for-missing-months) – Solarflare Sep 29 '16 at 09:19
  • Fiddle should load now. – Sonamor Sep 29 '16 at 10:22

2 Answers2

2

Ok, so in lieu of a functional SQLFiddle I will make a few assumptions. The country code exists in the same table as the grouped data.

If that is the case, why not use:

select DT1.CountryCode, count(DT2.ValueForCounting) as ReturnedCount
from (
select distinct CountryCode
from DataTable ) DT1
left join DataTable DT2
on DT1.CountryCode = DT2.CountryCode
and DT2.QueryConditions = 'Stuff'    -- Use the join condition instead of a where clause for anything to do with DT2
JohnHC
  • 10,935
  • 1
  • 24
  • 40
0

your fiddle link not loading,

but i guess my two different ideas about that,

  1. create function and manage it using if condition. or
  2. create view among month, country and mapping table and put month on left join

hope it works.

PSabuwala
  • 155
  • 1
  • 9