Home sql SQL: Sort by date

SQL: Sort by date

Author

Date

Category

Good day.
Please tell me how to sort all records by date, but not only ascending, but also starting today, for example:

December 6 (nearest date)

December 12

January 3

June 6

December 1

Another example:

For example today June 6th

June 6

December 1

December 6

December 12

January 3

Part of the solution I already have:

select * from db Order by Date_Format (Begin, '% m% d')

Using Where is not an option, because it is necessary to output all records.


Answer 1, Authority 100%

select B. * from
 (
 SELECT DB. *,
     Date_Format (Begin, '% m% d') - Date_Format (NOW (), '% M% d') AS Diff
  from db.
 ) B.
 ORDER BY (CASE WHEN DIFF & LT; 0 THEN 20000 + Diff Else Diff End)

In principle, you can without subquery, but I do not like to write long strings with Date_Format . But the basic idea: we get the number, “distance” from the current date to the test and if it is less than 0 (the date to current) then increase the “distance” so that it would be after all dates that After


Answer 2, Authority 100%

You need usual sorting by date + filter to show events in the subscription

select * from db
Where Begin & GT; Now ()
Order by Begin.

If you do not need to withdraw a year – decide this when the value is derived, and not in sorting.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions