【问题标题】:SQL calculate share of grouped variables to total countSQL计算分组变量占总数的份额
【发布时间】:2021-10-09 09:38:44
【问题描述】:

这可能很容易,机器人不知何故我无法得到想要的结果:

我的数据如下所示:我有一张大桌子,上面有已售商品。每个项目都有一个指定的类别(此处为 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 告诉我不能在一个请求中分组和使用窗口化。 我怎么能解决这个问题? 提前致谢

【问题讨论】:

    标签: sql impala


    【解决方案1】:

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

    我不使用 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
    

    【讨论】:

    • 谢谢!不过有一个小问题:我是否应该在with (...) 语句中添加过滤器where country='europe',以减少负载并提高执行速度,如果它预先计算所有内容,还是仅在语句末尾和你的例子一样?
    • 是的,你可以这样做,在这种情况下你不需要分区
    猜你喜欢
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多