【问题标题】:Join tables to get the empty rows连接表以获取空行
【发布时间】:2021-09-14 07:59:09
【问题描述】:

我有一张表包含每天的库存 (stock),另一张表包含所有位置 (locations)。货物表只有被填满的位置,但我还需要空架子来计算平均值等。这就是为什么我想加入两个数据框,以便我也得到空的)。

位置表如下所示:

Locations
A
B
C

库存表如下所示:

Date       Location quantity
2021-01-01 A        5
2021-01-01 B        5
2021-01-01 A        5
2021-01-02 A        5
2021-01-02 A        5

我想要什么:

Date       Location quantity
2021-01-01 A        5
2021-01-01 B        5
2021-01-01 A        5
2021-01-01 C        0 <-- new because on 01-01, there was no C
2021-01-02 A        5
2021-01-02 A        5
2021-01-02 B        0 <-- new because on 01-02, there was no C
2021-01-02 C        0 <-- new because on 01-02, there was no C

仅位置表就有超过一百万行。更复杂的是重复(同一位置的多个产品)。

【问题讨论】:

    标签: sql join merge google-bigquery


    【解决方案1】:

    使用cross join 生成行并使用left join 引入数据:

    select d.date, l.location, coalesce(s.quantity, 0)
    from (select distinct date from stock) d cross join
         locations l left join
         stock s
         on s.date = d.date and s.location = l.location;
    

    您可能有其他日期来源,或者可以使用数组生成它们。

    注意:此构造通常用于为每个位置和日期准确返回一行:

    select d.date, l.location, coalesce(sum(s.quantity), 0)
    from (select distinct date from stock) d cross join
         locations l left join
         stock s
         on s.date = d.date and s.location = l.location
    group by 1, 2;
    

    【讨论】:

    • @Charles 。 . .你有理由不接受这个答案吗?它似乎完全按照您的要求做,非常有效,并且是第一个答案。
    • 还不错,不知道是这样的
    【解决方案2】:

    考虑以下方法(更少的连接...)

    select date, location, sum(quantity) as quantity
    from (
        select date, location, quantity 
        from stock 
        union all
        select date, location, 0 as quantity
        from (select distinct date from stock), locations  
    )
    group by date, location          
    

    如果应用于您问题中的样本数据 - 输出是

    【讨论】:

      猜你喜欢
      • 2016-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多