【问题标题】:Sales amounts of the top n selling vendors by month in bigquerybigquery 中按月销售的前 n 个供应商的销售额
【发布时间】:2021-11-06 13:05:45
【问题描述】:

我在 bigquery 中有一个这样的表(260000 行):

vendor  date                  item_price
x       2021-07-08 23:41:10   451,5
y       2021-06-14 10:22:10   41,7
z       2020-01-03 13:41:12   74
s       2020-04-12 01:14:58   88
....

我真正想要的是按月对这些数据进行分组,然后找出当月排名前 20 位供应商的销售额总和。预期输出:

month     sum_of_only_top20_vendor's_sales
2020-01   7857
2020-02   9685
2020-03   3574
2020-04   7421
.....

【问题讨论】:

    标签: google-bigquery


    【解决方案1】:

    考虑以下方法

    select month, sum(sale) as sum_of_only_top20_vendor_sales
    from (
      select vendor, 
        format_datetime('%Y%m', date) month, 
        sum(item_price) as sale 
      from your_table
      group by vendor, month
      qualify row_number() over(partition by month order by sale desc) <= 20
    )
    group by month
    

    【讨论】:

    • 它有效。非常感谢。
    【解决方案2】:

    另一个可能在真正的大数据上表现出更好性能的解决方案:

    select month, 
      (select sum(sum) from t.top_20_vendors) as sum_of_only_top20_vendor_sales
    from (
      select 
        format_datetime('%Y%m', date) month, 
        approx_top_sum(vendor, item_price, 20) top_20_vendors
      from your_table
      group by month
    ) t
    

    或者稍微重构一下

    select month, sum(sum) as sum_of_only_top20_vendor_sales
    from (
      select 
        format_datetime('%Y%m', date) month, 
        approx_top_sum(vendor, item_price, 20) top_20_vendors
      from your_table
      group by month
    ) t, t.top_20_vendors
    group by month
    

    【讨论】:

    • 我学到了新东西。谢谢。
    • 你好。除了总销售额之外,我们可以添加这些供应商的其他数据吗?例如,一列=sum_of_only_top20_vendor_sales(这个已经存在),另一列= item_counts(第一列供应商销售的产品总数。)+另一列= discount_price(第一列供应商的总折扣金额.) 此信息(项目数量和折扣)在表中。我尝试了很多次,但都失败了。
    • 当然。请发布包含所有相关详细信息以及输入和预期输出示例的新问题,我们将很乐意为您提供帮助
    猜你喜欢
    • 2021-10-12
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多