T-SQL: Group timestamp by Year/Month

You can group datetime fields by year/month by using a simple ‘format’. Of course, there are other possibilities for doing this. See example below:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
declare @format varchar(100) = 'yyyy/MM'
SELECT format(timestamp,@format), count(*)
FROM [MY_DATABASE].[dbo].[MY_TABLE]
group by format(timestamp,@format)
order by format(timestamp,@format) desc;
declare @format varchar(100) = 'yyyy/MM' SELECT format(timestamp,@format), count(*) FROM [MY_DATABASE].[dbo].[MY_TABLE] group by format(timestamp,@format) order by format(timestamp,@format) desc;
  declare @format varchar(100) = 'yyyy/MM'
   SELECT  format(timestamp,@format), count(*)
  FROM [MY_DATABASE].[dbo].[MY_TABLE]
  group by format(timestamp,@format)
  order by format(timestamp,@format) desc;
Share your love