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

时间:2016-06-01 00:15:24

标签: sql sql-server business-intelligence

我有以下查询的输出

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组合来限制它。

1 个答案:

答案 0 :(得分:0)

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

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;

这假设每个日期在表格中出现一次。并且,d1和d2`可能已经在表中,因此可以使用这些表而不是子查询。