【问题标题】:Amazon Athena SQL:按国家/地区分组唯一用户 ID 值
【发布时间】:2022-01-20 12:27:42
【问题描述】:
  1. 针对单个表运行 AWS Athena SQL 查询,了解每个国家/地区的唯一用户总数。
  2. 允许用户出现在多个国家/地区,但每个国家/地区只能出现一次。

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

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

表结构:

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

谢谢。

【问题讨论】:

    标签: sql amazon-web-services group-by amazon-athena


    【解决方案1】:

    你在这里有一个多对多的关系——用户可以有多个国家,当然国家也可以有多个用户。我要做的是为国家和用户创建一个表,然后有一个名为 CountryUsers 的中间表,您在其中引用 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;
    

    【讨论】:

    • 感谢您的解决方案。我更新了我的问题,以澄清我正在使用 Amazon Athena 并且外键不是一个选项。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-06
    相关资源
    最近更新 更多