SQL计算总计和小计数但唯一

SQL to calculate the overall total and sub total number but unique

我有一个示例数据如下。

我想计算每个城市的用户数和每个国家/地区的用户数。

这是我想要的:

如何在 BigQuery 中尽可能简单地实现它?

万分感谢!

您可以使用解析函数如下:

select distinct country, city,
       count(distinct username) over (partition by country, city) as distinct_users_per_city,
       count(distinct username) over (partition by country) as distinct_users_per_country
  from your_Table t

I want to calculate user count per city and user count per country

我觉得来自 TokyoJessie 和来自 OkinawaJessie 是两个不同的用户,在国家/地区计数中需要这样计算! ChicagoJackNew York!

Jack 也是如此

下面的代码就是这样做的

select distinct country, city,
  count(distinct username) over (partition by country, city) as user_count_per_city,
  count(distinct username || '|' || city) over(partition by country) as user_count_per_country
from `project.dataset.table`    

如果应用于您问题中的示例数据 - 输出为

由于上述原因,这与您的(问题中的expected/presented)不同