缺失日期的零填充数据

Zero Fill Data for Missing Dates

我有两个表:

Cust    Sales   Week
123     4       1/8/2015
123     3       1/22/2015
234     4       1/1/2015

.

Week
1/1/2015
1/8/2015
1/15/2015
1/22/2015

我想将它们组合起来,以便每个 Cust 都有每个日期,并且在没有销售的地方用 0 填充。

Cust    Sales   Week
123     4       1/1/2015
123     0       1/8/2015
123     0       1/15/2015
123     3       1/22/2015
234     4       1/1/2015
234     0       1/8/2015
234     0       1/15/2015
234     0       1/22/2015

有什么办法可以'select distinct(Cust)'并以某种方式加入他们吗?

您可以在 table 日期 left join 并在销售栏中使用 isnull。在 Netezza 中使用等效的 isnull

select t1.cust, isnull(t1.sales,0), t2.week
from daystable2 t2 left join salestable1 t1 on t1.week = t2.week

我认为这会成功

SELECT week, cust, COALESCE(sales, 0)
FROM week_tbl a LEFT JOIN cust_table b
ON a.week = b.week

首先,使用 cross join 生成您想要的行。然后使用 left join:

引入你想要的数据
select c.cust, w.week, coalesce(t.sales, 0) as sales
from weeks w cross join
     (select distinct cust from t) c left join
     t
     on t.cust = c.cust and t.week = w.week;