连接表以获取空行

Join tables to get the empty rows

我有一个 table 包含每天的库存 (stock) 和另一个包含所有位置 (locations)。商品 tables 只有已填满的位置,但我还需要空货架来计算平均值等。这就是为什么我想加入两个数据框,这样我也得到空的)。

位置 table 看起来像:

Locations
A
B
C

股票 table 看起来像:

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

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

使用 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;

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

注意:此构造通常用于 return 每个位置和日期恰好一行:

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;

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

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          

如果应用于您问题中的示例数据 - 输出为