添加這個問題是關係到this SO post使用生產日期表中缺少的行
而不是使用遞歸CTE如何添加缺失數據(經認定失蹤日期)使用DimDates表?
我有以下兩個表:
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
這就是我已經結束了。標記答案的組合AMD的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]
)
'CROSS JOIN'做同樣的事情嗎? - 我補充說的是獲得笛卡爾產品 – whytheq
nah - 'CROSS JOIN'不是我用過的;所以你的評論是有效的 - 我將編輯OP – whytheq
在你的問題你想'添加'缺少的行。從你的編輯中,我猜你只是在選擇時而不是插入缺失的行?如果是這樣,這是一個簡單得多的模板'SELECT dates.date,categories.category,ISNULL(data.val,0)FROM日期CROSS JOIN類別LEFT JOIN數據ON data.date = dates.date AND data.category = categories。 *** [不是每件事都需要一個完整的外部聯接。] *** – MatBailie