HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Grouping data by MONTH on DATETIME column in SQL Server

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
columngroupingsqlmonthserverdatadatetime

Problem

I have a table Employee which has the columns Id, Date of joining and Name

Date of joining is a DATETIME column.

I want to know how many users have joined in the month of October?

Solution

If you're just looking for October regardless of the year, then the easy way would be to just COUNT the records from that month:

SELECT COUNT(*) AS NumberOfJoiners FROM Employee WHERE MONTH(DateOfJoining) = 10;


or

SELECT COUNT(*) AS NumberOfJoiners FROM Employee WHERE DATEPART(MONTH, DateOfJoining) = 10;


If you want to group by year, then you'll need a group by clause, otherwise October 2013, 2014, 2015 etc would just get grouped into one row:

SELECT 
  DATEPART(YEAR, DateOfJoining) AS YearOf Joining, 
  COUNT(*) AS NumberOfJoiners 
FROM Employee
WHERE DATEPART(MONTH, DateOfJoining) = 10
GROUP BY DATEPART(YEAR, DateOfJoining);

Code Snippets

SELECT COUNT(*) AS NumberOfJoiners FROM Employee WHERE MONTH(DateOfJoining) = 10;
SELECT COUNT(*) AS NumberOfJoiners FROM Employee WHERE DATEPART(MONTH, DateOfJoining) = 10;
SELECT 
  DATEPART(YEAR, DateOfJoining) AS YearOf Joining, 
  COUNT(*) AS NumberOfJoiners 
FROM Employee
WHERE DATEPART(MONTH, DateOfJoining) = 10
GROUP BY DATEPART(YEAR, DateOfJoining);

Context

StackExchange Database Administrators Q#81823, answer score: 7

Revisions (0)

No revisions yet.