我有一个包含多个表的数据库,我已将两个表连接在一起并且工作正常但我现在想要返回半小时间隔的数据!我已经阅读了很多关于此的文章,我似乎无法让它发挥作用。下面显示了我的数据库的示例
下面是我为加入两个表而编写的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
我尝试了很多例子,所以任何指导都会受到赞赏!
答案 0 :(得分:4)
您可以使用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)
今天在午夜开始计算&#34;&#34;并且DATEADD(day,DATEDIFF(day,0,CURRENT_TIMESTAMP),1)
计算&#34;明天在午夜开始&#34;这些与TimestampUTC
的比较现在可能会从该列的索引中受益。
答案 1 :(得分:2)
添加到您的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))
答案 2 :(得分:1)
如果您想要半小时间隔的数据,那么您可以使用日期时间字段的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;
我还修复了您的查询,因此您没有未定义的表别名,例如table1
。