简体   繁体   中英

Order by birthday, disregarding year

How do you make a query where you ORDER BY birthday disregarding the year altogether. I need to eliminate/disregard the year and ORDER BY birthdate month and birthdate day from today's date in either ASC or DESC.

The below won't work because the years of the birthdate come into play. The below example shows what happens when the year is regarded:

John   01/02/1974
Billy  11/15/2000
Ally   06/25/2008

SELECT * FROM users ORDER BY birthdate

Expected results when ordering by birthday:

John   01/02/1974
Ally   06/25/2008
Billy  11/15/2000

EDIT: @AaronBertrand's comment is correct, day-of-year doesn't hold for leap years. You could use his solution. Another way is to order by month and day, like:

SELECT * FROM users ORDER BY month(birthdate), day(birthdate)

This will normalize all dates to the year 2000:

ORDER BY DATEADD(YEAR, 2000-YEAR(birthday), birthday);

This will handle leap year babies correctly.

尝试

SELECT * FROM users ORDER BY SUBSTRING(birthdate, 1, 5);

Try this query

It order the birthdate in ascending order

SELECT `id`, `teacher_name`, `phn_num`, `date_of_birth`, `date_of_birth` + INTERVAL(YEAR(CURRENT_DATE()) - YEAR(`date_of_birth`)) + 0 YEAR AS currbirthday, `date_of_birth` + INTERVAL(YEAR(CURRENT_DATE()) - YEAR(`date_of_birth`)) + 1 YEAR AS nextbirthday FROM `teacher_details` ORDER BY CASE WHEN currbirthday >= CURRENT_DATE() THEN currbirthday ELSE nextbirthday END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM