Home >Database >Mysql Tutorial >How to Efficiently Round T-SQL Time Values to the Nearest 15-Minute Interval?
Exact calculation: Round T-SQL time values to the nearest 15 minute interval
When dealing with time-based data in T-SQL, it is often necessary to round values to a specific time interval. A common requirement is to round HH:MM values to the nearest 15 minute interval.
Efficient rounding method
An efficient way to round time values to the nearest 15-minute interval without relying on complex UDF or CASE statements, instead utilizing the DATEADD and DATEDIFF functions. This method includes:
Example
Apply this method to your specific need for calculations using the CONVERT, DATEADD and DATEDIFF functions and you will get the following query:
<code class="language-sql">SELECT DATEADD(MINUTE, ROUND(DATEDIFF(MINUTE, 0, CONVERT(CHAR(8), DATEADD(n, SUM(DATEDIFF(n, starttime, stoptime)), 0), 108)) / 15.0, 0) * 15, 0)</code>
This calculation rounds the HH:MM time value exactly to the nearest 15 minute interval, ensuring that a value like 00:08:00 becomes 00:15:00 and 00:07:00 becomes 00: 00:00.
Other methods
While the DATEADD and DATEDIFF methods are efficient and accurate, there are several other methods you can consider for rounding time values in T-SQL:
Use the ROUND function and specify the interval:
<code class="language-sql"> ROUND(time_value, 15)</code>
Using SQL Server 2012’s FLOOR function:
<code class="language-sql"> FLOOR(DATEADD(MINUTE, time_value, 0))</code>
The above is the detailed content of How to Efficiently Round T-SQL Time Values to the Nearest 15-Minute Interval?. For more information, please follow other related articles on the PHP Chinese website!