【问题标题】:Scala: Using a spark sql function when selecting column from a dataframeScala:从数据框中选择列时使用 spark sql 函数
【发布时间】:2019-07-17 04:38:50
【问题描述】:

我有两个表/数据框:AB

A 有以下列:cust_id, purch_date

B 有一列:cust_id, col1(不需要 col1)

以下示例显示了每个表的内容:

Table A
cust_id  purch_date
  34564  2017-08-21
  34564  2017-08-02
  34564  2017-07-21
  23847  2017-09-13
  23423  2017-06-19


Table B
cust_id  col1
  23442     x
  12452     x
  12464     x  
  23847     x
  24354     x

我想选择cust_idpurch_date 的第一天,其中B 中没有选定的cust_id

这可以通过以下命令在 SQL 中实现:

select a.cust_id, trunc(purch_date, 'MM') as mon
from a
left join b
on a.cust_id = b.cust_id
where b.cust_id is null
group by cust_id, mon;

以下将是输出:

Table A
cust_id  purch_date
  34564  2017-08-01
  34564  2017-07-01
  23423  2017-06-01

我尝试了以下方法在 Scala 中实现相同的功能:

import org.apache.spark.sql.functions._

a = spark.sql("select * from db.a")
b = spark.sql("select * from db.b")

var out = a.join(b, Seq("cust_id"), "left")
           .filter("col1 is null")
           .select("cust_id", trunc("purch_date", "month"))
           .distinct()

但我遇到了不同的错误,例如:

error: type mismatch; found: StringContext required: ?{def $: ?}

我被困在这里,无法在网上找到足够的文档/答案。

【问题讨论】:

    标签: scala apache-spark dataframe sql-function


    【解决方案1】:

    Select 应该包含Columns 而不是Strings

    输入:

    df1:
    +-------+----------+
    |cust_id|purch_date|
    +-------+----------+
    |  34564|2017-08-21|
    |  34564|2017-08-02|
    |  34564|2017-07-21|
    |  23847|2017-09-13|
    |  23423|2017-06-19|
    +-------+----------+    
    
    df2:
    +-------+----+
    |cust_id|col1|
    +-------+----+
    |  23442|   X|
    |  12452|   X|
    |  12464|   X|
    |  23847|   X|
    |  24354|   X|
    +-------+----+
    

    如下更改您的查询:

    df1.join(df2, Seq("cust_id"), "left").filter("col1 is null")
    .select($"cust_id", trunc($"purch_date", "MM"))
    .distinct()
    .show()
    

    输出:

    +-------+---------------------+
    |cust_id|trunc(purch_date, MM)|
    +-------+---------------------+
    |  23423|           2017-06-01|
    |  34564|           2017-07-01|
    |  34564|           2017-08-01|
    +-------+---------------------+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-08
      • 1970-01-01
      • 1970-01-01
      • 2020-03-21
      • 1970-01-01
      • 2021-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多