[英]How to create a single date column from multiple date column with start date and end date?
[英]create start and end date columns seperately from a single date column
我的日期列包含所有DepartmentID
的两个日期,一个是start_date
,另一个是end_date
。 output 将有两列用于开始日期和结束日期。 我想使用 SQL window function 或 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
预计 Output
Employee ID DateStart DateEnd DepartmentID
10001 20130101 20131201 001
10001 20131201 20141001 002
10001 20141001 Null 003
假设您将 dataframe 注册为名为“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)
不确定为什么 Department 003 的DateEnd
是Null
。 根据我对你的问题的理解,它应该是20141201
。 这是一个使用分组依据和聚合的 scala 版本。 最小是开始日期,最大是结束日期,如果只有一行,我们将结束设置为 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|
+------------+-----------+---------+--------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.