Return 每小时和半小时数据

Return hourly and half hourly data

我有一个包含许多表的数据库,我已将其中两个表连接在一起并且工作正常,但我现在想要 return 以半小时为间隔的数据!我已经阅读了很多关于这方面的文章,但我似乎无法让它发挥作用。下面显示了我的数据库的示例

下面是我写的SQL连接两个表

SELECT     
 Table2.SourceID, 
 Table2.Value, 
 Table1.Name, 
 Table2.TimestampUTC
 FROM         Table2 INNER JOIN
                  Source ON Table1.SourceID = Table1.ID 
 Where Table2.Value is not NULL
 ORDER BY Table2.TimestampUTC DESC

我已经尝试了很多例子,所以任何指导将不胜感激!

您可以使用 DATEPART 函数从 datetime 值中提取分钟:

SELECT     
 Table2.SourceID, 
 Table2.Value, 
 Table1.Name, 
 Table2.TimestampUTC
 FROM         Table2 INNER JOIN
                  Source ON Table1.SourceID = Table1.ID 
 Where Table2.Value is not NULL
 and DATEPART(minute,Table2.TimestampUTC) in (0,30)
 ORDER BY Table2.TimestampUTC DESC

(通常,建议您不要将函数应用于列,这样索引可能会有用,但是,鉴于此查询的性质,不太可能找到一种方法来编写它能够无论如何都受益于索引)


如果您只需要今天的行,则可以应用额外的过滤器:

SELECT     
 Table2.SourceID, 
 Table2.Value, 
 Table1.Name, 
 Table2.TimestampUTC
 FROM         Table2 INNER JOIN
                  Source ON Table1.SourceID = Table1.ID 
 Where Table2.Value is not NULL
 and DATEPART(minute,Table2.TimestampUTC) in (0,30)
 and Table2.TimestampUTC >= DATEADD(day,DATEDIFF(day,0,CURRENT_TIMESTAMP),0)
 and Table2.TimestampUTC < DATEADD(day,DATEDIFF(day,0,CURRENT_TIMESTAMP),1)
 ORDER BY Table2.TimestampUTC DESC

其中 DATEADD(day,DATEDIFF(day,0,CURRENT_TIMESTAMP),0) 计算 "today at the starting midnight",DATEADD(day,DATEDIFF(day,0,CURRENT_TIMESTAMP),1) 计算 "tomorrow at the starting midnight",这些与 TimestampUTC 的比较现在可能可以从该列的索引中获益.

使用 DatePart Function

很容易做到这一点

添加到您的 where 子句:

AND DATEPART(minute, TIMESTAMP) in (0, 30)

要过滤特定日期,请添加:

//Converting to varchar with sytle 101 strips off the time values, then we convert it back to a datateime for comparison
AND CONVERT(datetime, CONVERT(VARCHAR, TIMESTAMP, 101)) = '1/1/2015'

要过滤“今天”,请添加:

//Converting to varchar with sytle 101 strips off the time values, then we convert it back to a datateime for comparison
AND CONVERT(datetime, CONVERT(VARCHAR, TIMESTAMP, 101)) = CONVERT(datetime, CONVERT(VARCHAR, GETDATE(), 101))

如果您想要半小时间隔的数据,那么您可以使用日期时间字段的 minute 组件:

SELECT t2.SourceID, t2.Value, s.Name, t2.TimestampUTC
FROM Table2 t2 INNER JOIN
     Source s
     ON t2.SourceID = t2.ID 
WHERE t2.Value is not NULL AND
      datepart(minute, t2.TimestampUTC) in (0, 30)
ORDER BY t2.TimestampUTC DESC;

我还修复了您的查询,因此您没有未定义的 table 别名,例如 table1.