I have user login data with timestamps and what I would like to do is get a histogram of logins by year, but with the year starting at an arbitrary date. For example, I want the following sort of information:
1 May 2005 - 30 Apr 2006 | 525
1 May 2006 - 30 Apr 2007 | 673
1 May 2007 - 30 Apr 2008 | 892
1 May 2006 - 30 Apr 2009 | 1047
The labels in the first column are not important, but the date ranges are. I know I can break it down by strait years with:
SELECT YEAR([date]) AS [year], COUNT(*) AS cnt
FROM logins
GROUP BY YEAR([date])
ORDER BY [year]
But that doesn’t give me the data ranges I want. How can this be done?
EDIT – apologies, you are correct. Here is a fixed version (I should have used a test table to start with…)
Change the datediff units if you want more granularity than days.
EDIT #2 – ok, here is a more robust solution that handles leap years 🙂
EDIT #3 – Actually this doesn’t handle leap years, instead it allows for variable intervals of time to be specified. Go with dateadd(year, 1, @baseDate) for the leap year safe approach.