[英]SQL Query by time interval
So I have used this post as a reference, however I would like to count all the rows based on a 15 minute time period. 所以我使用这篇文章作为参考,但我想根据15分钟的时间段计算所有行。
Here is what I have so far: 这是我到目前为止:
SELECT DateAdd(minute, DateDiff(minute, 0, [datetime]), 0) as Timestamp,
Count(*) as Tasks
FROM [table]
GROUP BY DateAdd(minute, DateDiff(minute, 0, [datetime]), 0)
ORDER BY Timestamp
This is great for getting rows per minute, however I need 15 minutes... So I change: 这非常适合每分钟获取行数,但是我需要15分钟......所以我改变了:
DateAdd(minute, DateDiff(minute, 0, [datetime]), 0)
to 至
DateAdd(minute, DateDiff(minute, 0, [datetime]), 15)
however that is just pushing the date 15 days ahead. 然而,这只是推迟15天的日期。
Any help is appreciated! 任何帮助表示赞赏!
To get 15 minutes, divide by 15 (and then multiply again): 得到15分钟,除以15(然后再乘以):
SELECT DateAdd(minute, 15*(DateDiff(minute, 0, [datetime]) / 15), 0
) as Timestamp,
Count(*) as Tasks
FROM [table]
GROUP BY (DateDiff(minute, 0, [datetime]) / 15)
ORDER BY Timestamp;
SQL Server does integer division. SQL Server执行整数除法。 If you want to be unambiguous about your intentions, use FLOOR()
. 如果您想明确自己的意图,请使用FLOOR()
。
SELECT ROUND(DATEDIFF(SECOND,{d '1970-01-01'},[datetime])/(15 * 60),0) as Timestamp,
Count(*) as Tasks
FROM [table]
GROUP BY ROUND(DATEDIFF(SECOND,{d '1970-01-01'},[datetime])/(15 * 60),0)
ORDER BY Timestamp
Here is an alternative in case integer division causes an issue for you. 如果整数除法导致问题,这是一个替代方案。 It casts the datetime as a float and then uses floor(). 它将datetime转换为float,然后使用floor()。
SELECT convert(varchar,cast(round(floor(cast([datetime] as float(53))*24*4)/(24*4),5) as smalldatetime),108) as Timestamp,
Count(*) as Tasks
FROM [table]
GROUP BY convert(varchar,cast(round(floor(cast([datetime] as float(53))*24*4)/(24*4),5) as smalldatetime),108)
ORDER BY Timestamp
I normally change the (24*4) to 96 (the number of 15 minute intervals in a day), but thought I'd leave it so people can see how to adapt it for other time periods. 我通常会将(24 * 4)更改为96(一天中15分钟的间隔数),但我想我会离开它,以便人们可以看到如何在其他时间段内调整它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.