Amazon Athena SQL:按国家/地区对唯一用户 ID 值进行分组

Amazon Athena SQL: Group unique user id values by country

  1. 运行 AWS Athena SQL 针对单个 table 查询每个国家/地区的唯一用户总数。
  2. 允许用户出现在多个国家,但每个国家只能出现一次。

此查询 returns 所有国家/地区的唯一用户,但不允许一个用户在多个国家/地区是唯一的:

select
    country_code,
    count(user_id) as unique_users_per_country
from
    user_data
group by
    country_code
order by
    country_code asc

Table结构:

|Column Name|Data Type|
|timestamp|bigint|
|user_id|string|
|country_code|string|

谢谢。

你在这里有一个多对多的关系 - 用户可以有多个国家和国家当然可以有多个用户。我要做的是为国家和用户创建一个 table,然后有一个名为 CountryUsers 的中间 table,您在其中引用 user_id 和 country_id 作为外键。那么你必须像这样加入:

select users.id as userId, countries.id as countryId 
from users left join countryusers on countryusers.user_id = users.id
 left join countries on countryusers.country_id = countries.id order by countryId;

您尝试过在 COUNT 中使用 DISTINCT 吗?

select
    country_code,
    count(distinct user_id) as unique_users_per_country
from
    user_data
group by
    country_code
order by
    country_code asc