Sample Header Ad - 728x90

Sorting by month by chronological occurrence when the year doesn't matter?

2 votes
3 answers
8725 views
Given a table with a date column, and given a query that selects dates in a given range of the year (like "November 20th through February 20th"), and where the year portion of the date doesn't matter (such as upcoming birthdays), how can the results be sorted by month in the correct chronological order for the selected time range? For example, if the query grabs all dates between November 20th and February 20th regardless of year, it should sort them in the order: Nov -> Dec -> Jan -> Feb But a regular sort by month actually produces: Jan -> Feb -> Nov -> Dec Or an inverted sort produces: Dec -> Nov -> Feb -> Jan both of which are wrong. Here's a sample query with a three day range at the end of the year: SELECT EventDate FROM Events WHERE TIMESTAMPDIFF(YEAR, EventDate, "2012-12-28" + INTERVAL 3 DAY) > TIMESTAMPDIFF(YEAR, EventDate, "2012-12-28" - INTERVAL 1 DAY) ORDER BY DATE_FORMAT(EventDate, "%m-%d") DESC It produces: 2012-01-01 2008-01-01 2008-01-01 1987-01-02 1994-12-28 Where it should produce: 1994-12-28 2012-01-01 2008-01-01 2008-01-01 1987-01-02 Is there a way to get it to sort by month and day in a "going forward from range start" order? I searched here and on SO but didn't find an answer that dealt with both year end wrapping of months and a scenario where the year in the date field isn't relevant for sorting. **Update**: The range should always sort forward, so if the range is Feb to Nov, it does a standard sort of Feb - > Mar -> Apr .... If the range is Nov to Feb, it sorts Nov -> Dec -> Jan .... Although I don't anticipate that being an issue since I don't need to query more than a 3 month window.
Asked by Nick (301 rep)
May 30, 2016, 11:59 AM
Last activity: Jun 21, 2019, 04:20 PM