使用 Lag 分析函数查找丢失的小时
Posted
技术标签:
【中文标题】使用 Lag 分析函数查找丢失的小时【英文标题】:Fing the missing hour with Lag analytique function 【发布时间】:2014-11-14 11:42:39 【问题描述】:我必须在我的表中找到丢失的小时,因为频率 = 1 我必须每小时找到一条记录,如果不是这样,我必须显示丢失的小时。 这是我的代码
declare @StartDate datetime declare @EndDate datetime declare @now datetime set @now = getdate() set @StartDate = dateadd(day,-30,@now) set @EndDate = dateadd(day,-2,@now) Select Flow.Id,Flow.ComponentId, Frequency.Name frequencyName, Flow.MeasurementDate as MeasurementDate, LAG(MeasurementDate) OVER (ORDER BY MeasurementDate) LagValue, abs( DATEDIFF (hour, MeasurementDate, LAG(MeasurementDate) OVER (ORDER BY MeasurementDate) ) ) DifferenceDate , (CASE WHEN DATEDIFF (hour, MeasurementDate, LAG(MeasurementDate) OVER (ORDER BY MeasurementDate) ) > '1' THEN 'Yes' ELSE 'No' END) AS Gap into #tab1 FROM Data.dbo.Flow inner join Data.dbo.Component on flow.ComponentId = Component.Id inner join Data.dbo.Frequency on Flow.Frequency = Frequency.Id Where flow.LoaderCode='TOT' and Flow.Frequency='1' and ScheduledVolume IS NOT NULL and MeasurementDate between @StartDate and @EndDate --and DATEDIFF (hour, MeasurementDate, LAG(MeasurementDate) OVER (ORDER BY MeasurementDate) ) >1 Group By Frequency.Name, Flow.MeasurementDate, Flow.ComponentId select * from #tab1
【问题讨论】:
这真的是你展示代码的方式吗? 我无法更好地展示我的代码,它会生成一条错误消息来格式化我的代码...@SubqueryCrunch 【参考方案1】:--if i right understood then try this
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
DECLARE @now DATETIME
IF OBJECT_ID('Tempdb..#tab1') IS NOT NULL
BEGIN
DROP TABLE #tab1
END
SET @now = GETDATE()
SET @StartDate = GETDATE() - 30
SET @EndDate = GETDATE() - 2
SELECT Flow.Id ,
Flow.ComponentId ,
Frequency.Name AS frequencyName ,
CONVERT(DATE, Flow.MeasurementDate) AS [Measurement Date] ,
DATEPART(HOUR, Flow.MeasurementDate) AS [Measurement Hour] ,
COALESCE(LAG(DATEPART(HOUR, Flow.MeasurementDate)) OVER ( PARTITION BY CONVERT(DATE, MeasurementDate) ORDER BY DATEPART(HOUR,
MeasurementDate) ),
0) AS [Measurement Previous Hour]
INTO #tab1
FROM Data.dbo.Flow
INNER JOIN Data.dbo.Component ON Flow.ComponentId = Component.Id
INNER JOIN Data.dbo.Frequency ON Flow.Frequency = Frequency.Id
WHERE Flow.LoaderCode = 'TOT'
AND Flow.Frequency = '1'
AND ScheduledVolume IS NOT NULL
AND CONVERT(DATE, MeasurementDate) BETWEEN CONVERT(DATE, @StartDate)
AND CONVERT(DATE, @EndDate)
SELECT T.* ,
CASE WHEN ( T.[Measurement Hour] - T.[Measurement Previous Hour] ) > 1
THEN ( T.[Measurement Hour] - T.[Measurement Previous Hour] - 1 )
ELSE 0
END AS [Missing Hours]
FROM #tab1a AS T
WHERE ( T.[Measurement Hour] - T.[Measurement Previous Hour] ) > 1
【讨论】:
以上是关于使用 Lag 分析函数查找丢失的小时的主要内容,如果未能解决你的问题,请参考以下文章