这个问题与此 SO 帖子有关
我如何使用 DimDates 表添加丢失的数据(通过日期视为丢失)而不是使用递归 CTE?
我有以下两个表:
create table the_table
(
[Date] datetime,
Category2 varchar(10),
Amount INT
)
insert into the_table
values
( '01 jan 2012', 'xx', 10),
( '03 jan 2012', 'yy', 50)
create table DimDate
(
[Date] datetime
)
insert into DimDate
values
( '01 jan 2012'),
( '02 jan 2012'),
( '03 jan 2012'),
( '04 jan 2012')
这些是我试图达到的结果。我没有为递归 CTE 烦恼,因为我错误地认为,使用我们的仓库 DimDate 表会更容易加载:
好的 - 我可能偶然发现了一个可能的解决方案 - 如果它是错误的,请戳以下漏洞:
select
coalesce(x.[Date], y.[Date]) AS Date ,
coalesce(x.Category2, y.Category2) AS Category2 ,
isnull(Amount,0) as Amount
from the_table x
full outer join
(
select
d.Date
, t.Category2
from
the_table t
cross join DimDate d
) y
on
x.Category2 = y.Category2
and
x.Date = y.Date
这就是我最终的结果。Aaron 帖子中标记的答案和 cte 的组合:
;WITH
Dates_cte ([Date]) AS
(
SELECT [Date] = DayMarker
FROM WHData.dbo.vw_DimDate x
WHERE
x.DayMarker >= (SELECT MIN([Date]) FROM #Data1 WHERE Period = 'Daily') AND
x.DayMarker <= GETDATE()
)
,Categories ([Operator], [Market], [Product], [Measure]) AS
(
SELECT DISTINCT
[Operator]
, [Market]
, [Product]
, [Measure]
FROM #Data1
WHERE [Period] = 'Daily'
)
INSERT INTO #Data1
SELECT
c.[Operator]
, c.[Market]
, c.[Product]
, [Period] = CONVERT(VARCHAR(100), 'Daily')
, d.[Date]
, c.[Measure]
, 0
FROM Dates_cte d CROSS JOIN Categories c
WHERE NOT EXISTS
(
SELECT *
FROM #Data1 AS T
WHERE
t.[Period] = 'Daily' AND
t.[Operator] = c.[Operator] AND
t.[Market] = c.[Market] AND
t.[Product] = c.[Product] AND
t.[Measure] = c.[Measure] AND
t.[Date] = d.[Date]
)