我需要检查表格中的大量数据,以确保我的Feed没有跳过任何内容。
基本上该表格包含以下列
ID日期时间价格
DateTime列中的数据在每个连续行中增加1分钟。我需要检查当前行的下一行,看看是否比该特定上下文中的查询高1分钟。
查询可能需要某种循环,然后获取下一行的副本并将其与当前的日期时间行进行比较,以确保它增加1分钟。
答案 0 :(得分:3)
我创建了一个与您的描述相匹配的测试表,并在每行之间插入了100行,每行1分钟,如下所示:
CREATE TABLE [Test] ([Id] int IDENTITY(1,1), [Date] datetime, [Price] int);
WITH [Tally] AS (
SELECT GETDATE() AS [Date]
UNION ALL
SELECT DATEADD(minute, -1, [Date]) FROM [Tally] WHERE [Date] > DATEADD(minute, -99, GETDATE())
)
INSERT INTO [Test] ([Date], [Price])
SELECT [Date], 123 AS [Price]
FROM [Tally]
然后我在中间删除了一条记录,以模拟丢失的一分钟:
DELETE FROM [Test]
WHERE Id = 50
现在我们可以使用此查询来查找丢失的记录:
SELECT
a.*
,CASE WHEN b.[Id] IS NULL THEN 'Next record is Missing!' ELSE CAST(b.[Id] as varchar) END AS NextId
FROM
[Test] AS a
LEFT JOIN [Test] AS b ON a.[Date] = DATEADD(minute,1,b.[Date])
WHERE
b.[Id] IS NULL
resullt将如下所示:
Id Date Price NextId
----------- ----------------------- ----------- ------------------------------
49 2013-05-11 22:42:56.440 123 Next record is Missing!
100 2013-05-11 21:51:56.440 123 Next record is Missing!
(2 row(s) affected)
问题的关键解决方案是将表连接到自身,但使用datediff查找应该在下一分钟找到的记录。该表的最后一条记录当然会报告缺少下一行,因为尚未插入。
答案 1 :(得分:1)
借用你可以使用的Q样本数据
WITH T
AS (SELECT *,
DATEDIFF(MINUTE, '20000101', [Date]) -
DENSE_RANK() OVER (ORDER BY [Date]) AS G
FROM Test)
SELECT MIN([Date]) AS StartIsland,
MAX([Date]) AS EndIsland
FROM T
GROUP BY G