T-SQL code for getting DateTime only contains month and year from any DateTime
Given a table Event
that contains a field of EventTime
type DateTime and that the value will contain date and time elements, I need to create a summary query that counts the number of events in each month.
The resulting Group By field type must also be Date Time with a 0 time element and set to the 1st day of the month.
This is what I have so far, but it is not very elegant and I am not sure if it is particularly efficient.
SELECT COUNT(1) AS [CountOfEvents],
DATEADD(d, 1 - DAY(EventTime), DATEADD(dd, 0, DATEDIFF(dd, 0, EventTime))) AS [Month]
FROM [Event]
GROUP BY DATEADD(d, 1 - DAY(EventTime), DATEADD(dd, 0, DATEDIFF(dd, 0, EventTime)))
Best deals for more efficiency or elegance?
+2
source to share
4 answers
by floors up to a month:
select dateadd(month,datediff(m,0,GETDATE()),0);
output:
-----------------------
2009-10-01 00:00:00.000
(1 row(s) affected)
try this:
SELECT
COUNT(*) as CountOF
,dateadd(month,datediff(m,0,EventTime),0)
FROM [Event]
GROUP BY dateadd(month,datediff(m,0,EventTime),0)
ORDER BY 2
+10
source to share