SQL join, query combined tables

SQL join, query combined tables

I need to know the number of users there are in each country by ‘iso_country_trigraph’. I have two tables, ‘countries’ and ‘metadata’. I need to query the ‘metadata’ table using the ‘iso_country_trigraph’ list from the ‘countries’ table because the ‘iso_country_digraph’ column in the ‘metadata’ table only contains an ‘iso_country_digraph’ for countries that have at least one user and the countries that do not have users changes daily. I need to return a value of zero for countries that do not have any users. I am only querying against a single days data at a time.

countries table:

| iso_country_digraph | iso_country_trigraph | 
| 'AF'                | 'AFG'                |

metadata table:

| iso_country_digraph | user_id  | 
| 'AF'                | '1234'   |

Query:

select 
     count(distinct metadata.user_id), countries.iso_country_digraph
from 
     metadata
join 
     countries
on 
     metadata.user_id = countries.digraph
order by 
     countries.digraph

Desired output:

| iso_country_trigraph  | user_count    | 
| 'AFG'                 | '1234567'     |
| 'ALB'                 | '15447'       |
| 'BFA'                 | '254473'      |

Thank you.

You may also like...