回顾这个SO 帖子
如果有一个分组类别“类别”,为简单起见,可以是 X 或 Y - 修改此脚本是否是一件小事,以便为每个类别添加缺失的日期?
我认为该类别需要添加到 CTE 中吗?
换句话说,如果我有以下初始表:
...我如何获得以下信息:
将很快上传我的尝试
我已经调用了初始表#x。我希望适应如下递归 CTE 查询以包含字段类别:
DECLARE @MinDate DATETIME;
SET @MinDate = (SELECT Min(DATE) FROM #x)
DECLARE @MaxDate DATETIME;
SET @MaxDate = (SELECT Max(DATE) FROM #x)
;WITH times AS
(
SELECT @MinDate dt , 1 depth
UNION ALL
SELECT
DATEADD(d, depth, @MinDate) dt
, 1 + depth as depth
FROM times
WHERE DATEADD(d, depth, @MinDate) <= @MaxDate
)
SELECT
*
FROM
TIMES t
LEFT OUTER JOIN #X x
ON
t.dt = x.Date
好的 - 我已经绑定了一个 CROSS JOIN 但它错误地扩展了内容:
SELECT DISTINCT Category INTO #Cat FROM #x
DECLARE @MinDate DATETIME;
SET @MinDate = (SELECT Min(DATE) FROM #x)
DECLARE @MaxDate DATETIME;
SET @MaxDate = (SELECT Max(DATE) FROM #x)
;WITH times AS
(
SELECT
Category
, @MinDate dt
, 1 depth
FROM #Cat
UNION ALL
SELECT
c.Category
, DATEADD(d, depth, @MinDate) dt
, 1 + depth as depth
FROM
times t
CROSS JOIN #Cat c
--ON c.Category IS NOT NULL
WHERE DATEADD(d, depth, @MinDate) <= @MaxDate
)
SELECT
*
FROM
TIMES
这似乎工作正常:
SELECT DISTINCT Category INTO #Cat FROM #x
DECLARE @MinDate DATETIME;
SET @MinDate = (SELECT Min(DATE) FROM #x)
DECLARE @MaxDate DATETIME;
SET @MaxDate = (SELECT Max(DATE) FROM #x)
;WITH times AS
(
SELECT
Category
, @MinDate dt
, 1 depth
FROM #Cat
UNION ALL
SELECT
Category
, DATEADD(d, depth, @MinDate) dt
, 1 + depth as depth
FROM
times t
WHERE DATEADD(d, depth, @MinDate) <= @MaxDate
)
SELECT
*
FROM
TIMES