我從下表開始:
|date | first_cat | second_cat | price_change|
|:--------- | :--------- |: -------- | ----------:|
|30/05/2022 | old | test_2 | 0.94|
|31/08/2022 | old | test_3 | 1.24|
|30/05/2022 | old | test_2 | 0.90|
|31/08/2022 | old | test_3 | 1.44|
|30/05/2022 | new | test_1 | 1.94|
|30/06/2022 | new | test_4 | 0.54|
|31/07/2022 | new | test_5 | 1.94|
|30/06/2022 | new | test_4 | 0.96|
我想繼續計算按和分組的 price_changedate的乘積:first_catsecond_cat
|date | first_cat | second_cat | price_aggr |
|:--------- | :--------- |: -------- | ----------:|
|30/05/2022 | old | test_2 | 0.94*0.9|
|31/08/2022 | old | test_3 | 1.24*1.44|
|30/05/2022 | new | test_1 | 1.94|
|30/06/2022 | new | test_4 | 0.54*0.96|
|31/07/2022 | new | test_5 | 1.94|
我這樣做了:
SELECT
date,
first_cat,
second_cat
array_join(collect_list(price_change), "*") as price_aggr
FROM my_table
GROUP BY
date,
first_cat,
second_cat
但是,使用它會導致在表中包含文本運算式,而我想對該運算式進行評估,因此所需的結果如下:
|date | first_cat | second_cat | price_aggr |
|:--------- | :--------- |: -------- | ----------:|
|30/05/2022 | old | test_2 | 0.846|
|31/08/2022 | old | test_3 | 1.7856|
|30/05/2022 | new | test_1 | 1.94|
|30/06/2022 | new | test_4 | 0.5184|
|31/07/2022 | new | test_5 | 1.94|
我看到了一些想法,但他們使用“Pandas”和其他不適用的方法Spark SQL:
Spark 中的累積產品
我需要一個人做Spark SQL,我想避免轉換為Pandasand UDFs。
非常感謝!
uj5u.com熱心網友回復:
您需要price_change通過將組內的所有值相乘來進行聚合。使用 UDF 和 Dataframe API 非常簡單:
val product = udf { pcs: Seq[Double] => pcs.reduce(_ * _) }
my_table.groupBy($"date", "$first_cat", $"second_cat")
.agg(product(collect_list($"price_change")).as("price_aggr"))
.show
您也可以使用 SQL:
val product = udf { pcs: Seq[Double] => pcs.reduce(_ * _) }
spark.udf.register("product", product)
spark.sql("""
SELECT date, first_cat, second_cat, product(collect_list(price_change))
FROM my_table
GROUP BY date, first_cat, second_cat
""").show
好吧......如果你嚴格地想避免 UDF 并且不太關心可讀性,這也可以:
SELECT date, first_cat, second_cat,
exp(sum(ln(price_change))) as price_aggr
FROM my_table
GROUP BY date, first_cat, second_cat;
它利用了簡單的變換——兩個數的自然對數相加,然后對它們求冪就相當于乘法(->讀)。它不是超級可讀的,要小心潛在的精度損失——你的選擇。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/509908.html
標籤:sql阿帕奇火花
