python - 如何使用 Spark dataframe 获取某个范围内两个表之间的日期差异

标签 python

我正在尝试将下面的 Spark Sql 查询转换为 Spark Dataframe。

我有 Orders(OrderID, CustomerID, EmployeeID, OrderDate, ShipperID)Shippers(ShipperID, ShipperName,订单日期)

我的 Spark SQL 查询列出了每个托运人发送的订单数量:

 sqlContext.sql("SELECT Shippers.ShipperName, COUNT(Orders.ShipperID) 
    AS NumberOfOrders FROM Orders LEFT JOIN Shippers ON 
    Orders.ShipperID = Shippers.ShipperID  AND Shippers. OrderDate >= Orders.OrderDate 
    AND datediff(from_unixtime(cast(UNIX_TIMESTAMP(Shippers.OrderDate,
    'yyyy-MM-dd HH:mm:ss')as date)),from_unixtime(cast(UNIX_TIMESTAMP(Orders.
    OrderDate,'yyyy-MM-dd HH:mm:ss')as date))) BETWEEN 1 and 10 
    GROUP BY ShipperName")

我可以通过查询转换来处理整个连接组。问题在于日期时间转换并获得 1 到 10 天之间的差异。

这是我现在拥有的数据框。但我的选角出现错误

Shippers.alias("s").join(
    Orders.alias("o"),
    on = "ShipperID",
    how = "left"
).groupby(
    "s.ShipperName"
).select(datediff(from_unixtime(cast(unix_timestamp('OrderDate', 'yyyy-MM-dd HH:mm:ss').alias('unix_time'))).between(1,10))).agg(
    F.count(F.col("o.OrderID")).alias("NumberOfOrders")
).show()

有人可以帮我将上述 SQL 查询重构为 Spark Dataframe 吗?

最佳答案

您要执行的操作应该是这样的:

import pyspark.sql.functions as F

Orders.alias('o').join(
    Shippers.alias('s'),
    on = ["ShipperId"],
    how = "left"
).filter(
    (
        F.col("s.OrderDate") >= F.col("o.OrderDate")
    ) &
    (
        F.datediff(
            F.from_unixtime(
                F.unix_timestamp(
                    F.col('s.OrderDate'),
                    'yyyy-MM-dd HH:mm:ss'
                )
            ).cast('date'),
            F.from_unixtime(
                F.unix_timestamp(
                    F.col('o.OrderDate'),
                    'yyyy-MM-dd HH:mm:ss'
                )
            ).cast('date')
        ).between(1,10)
    )

).groupby(
    "ShipperName"
).agg(
    F.count(F.col("o.ShipperID")).alias("NumberOfOrders")
)

可能会根据错误进行一些更改,但逻辑应该是这样的

关于python - 如何使用 Spark dataframe 获取某个范围内两个表之间的日期差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52202097/

相关文章:

Python 正则表达式 : How to specify an optional match (for potentially empty sub expression)?

python - multiprocessing.Pool 与 maxtasksperchild 产生相等的 PID

python - Openpyxl 隐藏图例中的系列数据点

python - 用零填充 numpy 数组,并使用另一个数组作为 1 的索引

python - 确定第一组 CFG

python - 如何修复 jenkins 中的 python 模块导入错误

java - 如何使用 Protobuf 将数据从 Python 发送到 Java?

Python函数参数类型依赖关系

python - 从 Python 生成图形的最简单方法?

python - 为什么数据存储区日期时间在 App Engine 控制台与 App Engine 仪表板中看起来不同?