How to Group by Month in T-SQL Database: MS SQL Server Operators: DATEPART() GROUP BY Table of Contents Problem: Example: Solution: Discussion: Problem: You'd like to group records by month in a SQL Server database. Example: Our database has a table named furniture with data in the columns id, name, and production_timestamp. idnameproduction_timestamp 1double bed2022-02-01 11:45:23 2coffee table2022-02-01 11:46:13 3chest of drawers2022-01-22 17:22:05 Solution: You can use two DATEPART() functions to group records in a table by month and year. Here's the query you would write: SELECT DATEPART(YEAR, production_timestamp) AS year, DATEPART(MONTH, production_timestamp) AS month, COUNT(id) AS count FROM furniture GROUP BY DATEPART(MONTH, production_timestamp), DATEPART(YEAR, production_timestamp); Here’s the result of the query: yearmonthcount 202211 202222 Discussion: Grouping records by month is a very common operation in SQL Server. In our example, the number of products is totaled for each month of the year. You usually want to take into account both the year and the month of the date, i.e. you want to group events in January 2022 separately from events in January 2021. To group data by month in SQL Server, use the DATEPART() function. It extracts the given part (year, month, etc.) from the date. We use the function twice: once with the MONTH argument and once with the YEAR argument. This extracts the month and year (respectively) from the production timestamp. We combine the two calls to DATEPART() in the GROUP BY clause to group furniture by the month and year when they were produced. We use the same two calls to DATEPART() in the SELECT clause to display the label for the year and month. Recommended courses: SQL Basics in SQL Server Common Functions in SQL Server Recommended articles: SQL Server Cheat Sheet Top 29 SQL Server Interview Questions How to Learn T-SQL Querying How Does SQL GROUP BY Work? 5 Examples of GROUP BY SQL Date and Time Functions in 5 Popular SQL Dialects GROUP BY and Aggregate Functions: A Complete Overview Top 9 SQL GROUP BY Interview Questions See also: How to Get the Day from a Date in T-SQL How to Get the Month from a Date in T-SQL How to Get the Year from a Date in T-SQL How to Get Yesterday’s Date in T-SQL How to Group by Year in T-SQL Subscribe to our newsletter Join our monthly newsletter to be notified about the latest posts. Email address How Do You Write a SELECT Statement in SQL? What Is a Foreign Key in SQL? Enumerate and Explain All the Basic Elements of an SQL Query