SQL 用日期维度填充维度间隙

SQL filling dimensional gaps with date dimension

我有以下查询的输出

SELECT INTO #GroupedData
SUM(Amount) OVER (PARTITION BY Dim1, Dim2 ORDER BY DimDate) AS RunningTotal
SUM(Amount) AS Total
Dim1, Dim2, DimDate
FROM FactTable
GROUP BY Dim1, Dim2, DimDate

这给我留下了可能的漏洞,所以我有一个我可以加入的 CalendarTable

获取未来日期值或填补空白。但是我该如何考虑尺寸呢?

我知道这有可能产生许多行,因为它的 DimDate X Dim1 X Dim2 取决于您是否可以通过实际的 Dim 组合来限制它。

假设您在 table 某处 中有每个日期,那么您可以使用 cross join 生成行。然后 left join 从事实 table:

中引入行
select d1.dim1, d2.dim2, d.dimdate, sum(f.amount) as total,
       sum(sum(amount)) over (parition by d1.dim1, d2.dim2 order by d.dimdate) as runningtotal
from (select distinct dim1 from facttable) d1 cross join
     (select distinct dim2 from facttable) d2 cross join
     (select distinct dimdate from facttable) d left join
     facttable f
     on f.dim1 = d1.dim1 and f.dim2 = d2.dim2 and f.dimdate = d.dimdate
group by d1.dim1, d2.dim2, d.dimdate;

这确实假定每个日期在 table 中出现一次。而且,d1 和 d2` 可能已经在 table 中,因此可以使用这些 table 代替子查询。