如何生成缺失数据的间隙
我的数据结构如下:
使用以下 CTE:
WITH DateRange AS
(
SELECT CAST('2012-01-24 06:00' AS DATETIME) DateValue
UNION ALL
SELECT DATEADD(mi, 1, DateValue)
FROM DateRange
WHERE DATEADD(mi, 1, DateValue) <= '2012-01-24 12:00'
)
SELECT DateValue FROM DateRange
OPTION (MAXRECURSION 0)
我创建了一个“日期集”看起来像这样:
问题是:原始数据集不具有CTE 中的相应日期(在提供的示例中,数据中不存在 2012-01-24 6:00)。
对于这些缺失的数据点,我希望将“NULL”视为它们的值。我想我也许能够利用我生成的 CTE 中的日期,但我不确定如何做到这一点。
我尝试过类似的事情但没有成功:
SELECT C.DateValue, D.Value
FROM myCTE C
LEFT OUTER JOIN myData D ON C.DateValue = D.Date
ORDER BY C.DateValue ASC;
I have data that is structured as follows:
Using the following CTE:
WITH DateRange AS
(
SELECT CAST('2012-01-24 06:00' AS DATETIME) DateValue
UNION ALL
SELECT DATEADD(mi, 1, DateValue)
FROM DateRange
WHERE DATEADD(mi, 1, DateValue) <= '2012-01-24 12:00'
)
SELECT DateValue FROM DateRange
OPTION (MAXRECURSION 0)
I have created a "Date Set" that look like this:
The Issue Is: There is some data in the original data-set that does not have a corresponding date in the CTE (In the provided example, 2012-01-24 6:00 is not present in the data).
For these missing data points, I would like to see "NULL" as their value. I thought I might be able to leverage the dates in the CTE I generated, but I'm not sure how I can do this.
I have tried something like this with no success:
SELECT C.DateValue, D.Value
FROM myCTE C
LEFT OUTER JOIN myData D ON C.DateValue = D.Date
ORDER BY C.DateValue ASC;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我无法复制您所看到的问题。我创建了下面的查询并对其进行了测试,它工作正常 - 您可以在您的环境中测试它吗?
I can't replicate the issue you're seeing. I've created the query below and tested it and it works fine - can you test this in your environment?
您需要的是
RIGHT OUTER JOIN
,而不是LEFT OUTER JOIN
。左连接有空值,而右手边缺少数据;这里的左侧是myCTE
。You want a
RIGHT OUTER JOIN
, not aLEFT OUTER JOIN
. The left join has nulls where the right-hand side is missing data; the left-hand side here ismyCTE
.