Home > Database > Mysql Tutorial > How Can I Group Time Intervals in MS SQL 2008?

How Can I Group Time Intervals in MS SQL 2008?

Susan Sarandon
Release: 2025-01-15 14:52:43
Original
719 people have browsed it

How Can I Group Time Intervals in MS SQL 2008?

MS SQL 2008 Time Interval Grouping

When grouping time data in a SQL query, it is often useful to specify the desired grouping period. In MS SQL 2008 you can use DATEPART function for this purpose.

Group by hour, use the following code:

<code class="language-sql">GROUP BY DATEPART(HOUR, [Date])</code>
Copy after login

For 10 minute intervals, apply the following code:

<code class="language-sql">GROUP BY (DATEPART(MINUTE, [Date]) / 10)</code>
Copy after login

To remove milliseconds from Date output, use the CAST function:

<code class="language-sql">GROUP BY CAST([Date] AS DATE)</code>
Copy after login

Here is a complete example, grouping data by 10 minute intervals and removing milliseconds:

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

The above is the detailed content of How Can I Group Time Intervals in MS SQL 2008?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template