Sort upcoming birthdays based on current date

后端 未结 5 948
庸人自扰
庸人自扰 2020-12-06 08:01

I have the following table of people and their birthdays:

name        birthday
----------------------
yannis      1979-06-29
natalia     1980-08-19
kostas            


        
5条回答
  •  心在旅途
    2020-12-06 08:21

    Here is one way:

    • Calculate current year - year of birth
    • Add the resulting number of years to the date of birth
    • You now have the birthday this year, if this date has passed then add one more year
    • Sort the results by that date
    SELECT
        name,
        birthday,
        birthday + INTERVAL (YEAR(CURRENT_DATE) - YEAR(birthday))     YEAR AS currbirthday,
        birthday + INTERVAL (YEAR(CURRENT_DATE) - YEAR(birthday)) + 1 YEAR AS nextbirthday
    FROM birthdays
    ORDER BY CASE
        WHEN currbirthday >= CURRENT_DATE THEN currbirthday
        ELSE nextbirthday
    END
    

    Notes:

    • Today's birthdays appears first regardless of current time
    • February 29 birthday is treated equal to February 28 birthday for common years e.g.
      • On Jan/1/2019 both Feb 28 and Feb 29 birthdays (2019) are sorted equal
      • On Mar/1/2019 Feb 28 and Feb 29 birthdays (2020) are sorted as expected

    SQLFiddle

提交回复
热议问题