【问题标题】:doing join between two tables based on item,loc combinations根据 item,loc 组合在两个表之间进行连接
【发布时间】:2023-03-17 11:37:01
【问题描述】:

项目表:

item   loc    month    year
watch  delhi   1       2020
watch  delhi   2       2020
watch  delhi   4       2020
watch  delhi   5       2020
tv     mumbai  1       2020
tv     mumbai  2       2020
tv     mumbai  5       2020

月表:

month    year
  1      2020
  2      2020
  3      2020
  4      2020
  5      2020

我想使用右连接来连接项目和月份表......但这里有一些复杂性......我想要的是我想要每个项目的连接,loc 组合......即对于手表项目,它将是不同的联接,对于电视项目,它将是与月表不同的联接。

输出:

item   loc    month    year
watch  delhi   1       2020
watch  delhi   2       2020
null   null    3       2020
watch  delhi   4       2020
watch  delhi   5       2020
tv     mumbai  1       2020
tv     mumbai  2       2020
null   null    3       2020
null   null    4       2020
tv     mumbai  5       2020

【问题讨论】:

    标签: sql pyspark apache-spark-sql


    【解决方案1】:

    我更喜欢没有NULL 值的结果集。那将是:

    select il.item, il.loc, m.month, m.year
    from (select distinct item, loc from items) il cross join
         months m;
    

    如果你真的想要NULL 值,你可以使用额外的left join

    select i.item, i.loc, m.month, m.year
    from (select distinct item, loc from items) il cross join
         months m left join
         items i
         on i.item = il.item and i.loc = il.loc
    order by il.item, il.loc, m.year, m.month;
    

    order by 很重要,因此行将正确对应。

    【讨论】:

      猜你喜欢
      • 2014-02-15
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 2021-11-05
      • 1970-01-01
      • 1970-01-01
      • 2013-08-06
      • 2016-11-18
      相关资源
      最近更新 更多