SQL 计算分组变量占总数的份额

SQL calculate share of grouped variables to total count

这可能很简单,但我无法得到想要的结果:

我的数据如下所示:我有一个很大的 table 商品已售出。每个项目都分配了一个类别(此处为 A-D)和国家/地区。我想计算每个类别在欧洲销售了多少商品,以及该特定类别占总销售额的份额是多少

我的数据是这样的:

country item_id item_cat
Europe 1 A
Europe 2 A
Europe 3 B
Europe 4 B
Europe 5 C
Europe 6 C
Europe 7 C
USA 8 D
USA 9 D
USA 10 D

我想要的输出是这样的:

country item_cat cat_sales total_sales share
Europe A 2 7 0.29
Europe B 2 7 0.29
Europe C 3 7 0.43

我试过的是:

SELECT 
   country, 
   item_cat, 
   count(*) as cat_sales,
   count(*) OVER () as total_sales,
   cat_sales / total_sales as share
FROM data
where country='Europe'
group by item_cat

但是 SQL 告诉我不能在一个请求中分组和使用窗口化。 我怎么能解决这个问题? 提前致谢

有几种方法,一种是预先计算 CTE 中的总销售额,然后 select 从中计算剩余的总销售额。

我不使用 impala 但是在标准 SQL 中这应该可以工作

with tot as (
    select *, 
      Count(*) over(partition by country) * 1.0 as total_sales
    from t
)
select country, item_cat, 
    Count(*) as cat_sales, 
    total_sales,
    Round(Count(*) / total_sales, 2) as Share
from tot
where country='europe'
group by country, item_cat, total_sales