I need to run a query against a database and group the records by different date ranges. The data type of the date field is varchar
and in the format dd-MMM-yyyy
e.g. 19-Aug-2016
.
The date ranges are as follow: 13–18
, 19–35
, 36–55
and >55
. This range is determined by subtracting the current date from the date stored in the field.
e.g. if current date is 19-Aug-2016
and date stored in the database field is 18-Aug-2003
, the year difference will be 13
. So all the date differences between 13 and 18
will be grouped together, all date differences between 19 and 35
will be grouped together etc.
Best Answer
First let me say storing dates in a character column is a horrible horrible idea. Sorts won't work correctly, any form of date calculations are going to require actually casting back to a date anyway, and best of all you probably have bad data in there.
But assuming your table isn't overly large (performance on this is going to kill you because of the cast) and you don't have any bad data. This will work
V2.0 You'll probably get a bit better performance with this: