我有以下查询的输出
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组合来限制它。
答案 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`可能已经在表中,因此可以使用这些表而不是子查询。