【问题标题】:create start and end date columns seperately from a single date column与单个日期列分开创建开始和结束日期列
【发布时间】:2021-11-28 05:03:31
【问题描述】:

我的日期列包含所有DepartmentID 的两个日期,一个是start_date,另一个是end_date。输出将有两列用于开始日期和结束日期。我想使用 SQL 窗口函数或 Spark Dataframe 来实现。

输入

Employee ID      Date           DepartmentID    SupervisorID
10001            20130101          001             10009
10001            20130909          001             10019
10001            20131201          002             10018
10001            20140501          002             10017
10001            20141001          003             10015
10001            20141201          003             10014

预期输出

Employee ID    DateStart    DateEnd      DepartmentID
10001         20130101      20131201       001
10001         20131201      20141001       002
10001         20141001       Null          003

【问题讨论】:

  • 每个员工的每个部门是否正好有 2 行?

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


【解决方案1】:

假设您将数据框注册为名为“tmp”的临时视图,并运行以下 SQL 以获得预期结果。

    select EmployeeID,DateStart,
        lead(DateStart) over (order by DateStart) DateEnd,DepartmentID
    from
        (select EmployeeID,min(Date) DateStart,DepartmentID
        from tmp
        group by EmployeeID,DepartmentID)

【讨论】:

    【解决方案2】:

    不知道为什么部门 003 的 DateEndNull。根据我对您问题的理解,应该是20141201。这是使用 group by 和聚合的 scala 版本。 min 是开始日期,max 是结束日期,如果只有一行,我们将 end 设置为 null。

    df
        .groupBy("DepartmentID", "Employee ID")
        .agg(min('Date) as "DateStart", max('Date) as "DateEnd", count('*) as "count")
        .withColumn("DateEnd", when('count > 1, 'DateEnd))
        .drop("count").show(false)
    +------------+-----------+---------+--------+
    |DepartmentID|Employee ID|DateStart|DateEnd |
    +------------+-----------+---------+--------+
    |002         |10001      |20131201 |20140501|
    |003         |10001      |20141001 |20141201|
    |001         |10001      |20130101 |20130909|
    +------------+-----------+---------+--------+
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2022-01-25
      • 2021-08-22
      • 2023-03-17
      • 2021-06-20
      • 2018-10-16
      • 1970-01-01
      相关资源
      最近更新 更多