Home > Database > Mysql Tutorial > How to Group Time Intervals (Hourly or 10-Minute) in SQL Server?

How to Group Time Intervals (Hourly or 10-Minute) in SQL Server?

DDD
Release: 2025-01-15 14:56:47
Original
499 people have browsed it

How to Group Time Intervals (Hourly or 10-Minute) in SQL Server?

Time interval grouping in SQL Server

In data analysis, grouping data by time intervals is critical to identifying patterns and trends. This article explores how to implement time grouping in Microsoft SQL Server 2008, explaining how to group by hour or 10 minutes.

Group by hour or 10 minutes

To group times by hours, use the DATEPART(HOUR, [Date]) function. For a 10-minute interval, use (DATEPART(MINUTE, [Date]) / 10). The following modified query groups data by hour:

<code class="language-sql">SELECT MIN([Date]) AS RecT, AVG(Value)
FROM [FRIIB].[dbo].[ArchiveAnalog]
GROUP BY DATEPART(HOUR, [Date])
ORDER BY RecT</code>
Copy after login

For 10 minute intervals, use:

<code class="language-sql">SELECT MIN([Date]) AS RecT, AVG(Value)
FROM [FRIIB].[dbo].[ArchiveAnalog]
GROUP BY (DATEPART(MINUTE, [Date]) / 10)
ORDER BY RecT</code>
Copy after login

Remove milliseconds from date output

To exclude milliseconds from the output, use the DATEPART function again:

<code class="language-sql">SELECT MIN(DATEPART(HOUR, [Date])) AS RecT, AVG(Value)
FROM [FRIIB].[dbo].[ArchiveAnalog]
GROUP BY YEAR([Date]), MONTH([Date]), DAY([Date]), HOUR([Date])
ORDER BY RecT</code>
Copy after login

In this query, the DATEPART function is used on each date component to remove milliseconds.

The above is the detailed content of How to Group Time Intervals (Hourly or 10-Minute) in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template