【问题标题】:Find customer id(s) who spent maximum amount in a given month查找在给定月份中花费最大金额的客户 ID
【发布时间】:2018-08-09 01:37:19
【问题描述】:

我想计算 6 月份消费金额最高的客户 ID。

数据集:

May-2017-120-245.50                                
Jun-2017-124-21.50                                                                
Jun-2017-110-34.00                 
Jun-2017-120-200.00      
Jul-2017-124-546.50  
Jul-2017-110-1500.00  
Jun-2017-124-245.50

代码:

val spark = SparkSession.builder().appName("MapFunction").master("local").getOrCreate();
val data = spark.read.textFile("E:\\Sample - Copy.txt").rdd
val monthFilter = data.filter(line => line.contains("Jun"))
val ratings = monthFilter.map(x => (x.toString().split("-")(3),x.toString().split("-")(2)));

我不知道如何得到结果。有人可以帮我吗?

【问题讨论】:

    标签: scala apache-spark apache-spark-sql


    【解决方案1】:

    鉴于您的示例数据包含同一客户在给定月份的多次交易,以下解决方案首先将文本数据加载到 DataFrame 中,过滤目标年月,汇总每个客户的金额,最后获取总金额最大的行:

    // /path/to/textfile
    May-2017-120-245.50
    Jun-2017-124-21.50
    Jun-2017-110-34.00
    Jun-2017-120-200.00
    Jul-2017-124-546.50
    Jul-2017-110-1500.00
    Jun-2017-124-245.50
    
    import org.apache.spark.sql.functions._
    import org.apache.spark.sql.expressions.Window
    
    val df = spark.read.option("delimiter", "-").csv("/path/to/textfile").
      toDF("month", "year", "cust_id", "amount")
    
    df.
      where($"year" === "2017" && $"month" === "Jun").
      groupBy($"cust_id").agg(sum($"amount").as("total_amount")).
      withColumn("amountRank", dense_rank.over(Window.orderBy($"total_amount".desc))).
      where($"amountRank" === 1).
      show
    // +-------+------------+----------+
    // |cust_id|total_amount|amountRank|
    // +-------+------------+----------+
    // |    124|       267.0|         1|
    // +-------+------------+----------+
    

    请注意,dense_rank 用于涵盖多个客户的最大总金额相同的情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-11
      • 2020-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-28
      • 1970-01-01
      相关资源
      最近更新 更多