【问题标题】:PySpark/SQL joining on non unique keyPySpark/SQL 加入非唯一键
【发布时间】:2020-03-23 17:39:22
【问题描述】:

我有两个需要加入的事务表;但是,这两个表之间没有明确的联系:

对于 t1,我有:

unique_id | date | units

对于 t2 我有:

unique_id | date | store_id | transaction_key

我想要的输出是根据 store_id 获得单位;但是,当我在 t1 上使用 unique_id 和日期进行左连接时,在某些情况下,客户在同一天进行了多次交易,这给了我交易密钥的重复。

添加了示例数据和输出:

表一和表二:

当前输出:

期望的输出:

【问题讨论】:

  • 请提供样本数据和预期结果。
  • @GMB 嘿 GMB,已添加。感谢您对此的任何帮助。
  • 是 SQL 查询的“当前输出”吗?如果是这样,读者可以在问题中看到它吗?

标签: sql join pyspark


【解决方案1】:

我认为您想要一个left join,但将row_number() 作为匹配条件:

select t1.unique_id, t1.date, t1.units, t2.store_id, t2.transaction_key
from (
    select t1.*, row_number() over(partition by unique_id, date order by units) rn
    from table1 t1
) t1
left join (
    select t2.*, row_number() over(partition by unique_id, date order by transaction_key) rn
    from table2 t2
) t2
    on t2.unique_id = t.unique_id and t2.date = t1.date and t2.rn = t1.rn

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-02
    • 2011-01-16
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多