Ordering of Dates and retrieving results based on current date (Birth Day List) SQLite

后端 未结 2 440
情话喂你
情话喂你 2021-01-07 15:40

I have a date stored as string in a Sqlite column, the format is YYYY-MM-DD ( Not separated into three columns for year date and month) Now I have a requirement to make a qu

2条回答
  •  自闭症患者
    2021-01-07 16:03

    Following will do:

    SELECT *
    FROM _table
    ORDER BY SUBSTR(DATE('NOW'), 6)>SUBSTR(birthdate, 6), SUBSTR(birthdate, 6)
    

    Check it in SQL Fiddle.

    SUBSTR(date, 6) will remove year part from date. Birthdates must be sorted in MM-DD, but first should be shown those which will happen after today, and then those which happen before today.

    SUBSTR(DATE('NOW'), 6)>SUBSTR(birthdate, 6) will return 0 for birthdates MM-DD greater or equal to today MM-DD, 1 otherwise. So, first expression will ORDER past dates after comming date. Second parameter just ORDER dates by MM-DD.

    See step by step in SQL Fiddle.

提交回复
热议问题