aggregation - 如何在使用 CoPPer 按多个列值分组时对列进行聚合?
问题描述
我有一个包含某些产品当前库存的数据集:
+--------------+-------+
| Product | Stock |
+--------------+-------+
| chocolate | 300 |
| coal | 70 |
| orange juice | 400 |
+--------------+-------+
以及在另一个数据集中,当月和下个月每种产品多年来的销售额:
+--------------+------+-------+-------+
| Product | Year | Month | Sales |
+--------------+------+-------+-------+
| chocolate | 2017 | 05 | 55 |
| chocolate | 2017 | 04 | 250 |
| chocolate | 2016 | 05 | 70 |
| chocolate | 2016 | 04 | 200 |
| | | | | | | | |
| coal | 2017 | 05 | 40 |
| coal | 2017 | 04 | 30 |
| coal | 2016 | 05 | 50 |
| coal | 2016 | 04 | 20 |
| | | | | | | | |
| orange juice | 2017 | 05 | 400 |
| orange juice | 2017 | 04 | 350 |
| orange juice | 2016 | 05 | 400 |
| orange juice | 2016 | 04 | 300 |
+--------------+--------------+-------+
我想通过使用以下公式计算当月和下个月的预期销售额来计算下个月需要订购的库存:
ExpectedSales = max(salesMaxCurrentMonth) + max(salesMaxNextMonth)
然后订单将是
Orders = ExpectedSales * (1 + margin) - Stock
例如,保证金为 10%。
我尝试使用 对几列进行分组,GroupBy
如下所示,但它似乎是通过Stock
而不是聚合Product
:
salesDataset
.groupBy(Columns.col("Month"), Columns.col(“Product”))
.agg(Columns.max(“Sales”).as(“SalesMaxPerMonth”))
.agg(Columns.sum(“SalesMaxPerMonth”).as(SalesPeriod))
.withColumn(
“SalesExpected”,
Columns.col(“SalesPeriod”).multiply(Columns.literal(1 + margin)))
.withColumn(
“Orders”,
Columns.col(“SalesExpected”).minus(Columns.col(“Stock”)))
.withColumn(
“Orders”,
Columns.col(“Orders”).map((Double a) -> a >= 0 ? a: 0))
.doNotAggregateAbove()
.toCellSet()
.show();
解决方案
您在聚合方面得到了正确的逻辑,但是还有另一种构建方法,CellSet
您可以在其中提供一个地图来描述生成它的查询的位置。
salesDataset
.groupBy(Columns.col("Month"), Columns.col(“Product”))
.agg(Columns.max(“Sales”).as(“SalesMaxPerMonth”))
.agg(Columns.sum(“SalesMaxPerMonth”).as(SalesPeriod))
.withColumn(
“SalesExpected”,
Columns.col(“SalesPeriod”).multiply(Columns.literal(1 + margin)))
.withColumn(“Orders”, Columns.col(“SalesExpected”).minus(Columns.col(“Stock”)))
.withColumn(“Orders”, Columns.col(“Orders”).map((Double a) -> a >= 0 ? a: 0))
.doNotAggregateAbove()
.toCellSet(
Empty.<String, Object>map()
.put(“Product”,null)
.put(“Stock”, null))
.show();
where null
in a location 表示通配符*
。
推荐阅读
- powershell - 使用常用词选择文件夹名称
- python - 如何解决此调用异常错误?
- reactjs - Electron + React,将文件保存到本地目录使 React 重新加载
- python - ImportError:无法从“skimage”导入名称“metrics”
- linux - XKB mod3 不断映射到 Mode_switch 而不是 ISO_Level5_Shift
- php - php提交的Xss预防
- r - 如何在 R 的数据框中添加新列并使用现有列?
- javascript - Javascript 从嵌套对象构建嵌套对象
- javascript - 从动态创建的表单输入上传多个文件
- python - 从 AVRO 加载到 BigQuery - 在目标表中指定十进制类型