Order by descending date - month, day and year

前端 未结 6 592
Happy的楠姐
Happy的楠姐 2020-12-05 03:45

This seems stupid but, I simply need a list of dates to be ordered with the most recent date at top. Using order by DESC doesn\'t seem to be working the way I w

相关标签:
6条回答
  • 2020-12-05 04:31

    You have the field in a string, so you'll need to convert it to datetime

    order by CONVERT(datetime, EventDate ) desc
    
    0 讨论(0)
  • 2020-12-05 04:33

    If you restructured your date format into YYYY/MM/DD then you can use this simple string ordering to achieve the formating you need.

    Alternatively, using the SUBSTR(store_name,start,length) command you should be able to restructure the sorting term into the above format

    perhaps using the following

    SELECT     *
    FROM         vw_view
    ORDER BY SUBSTR(EventDate,6,4) + SUBSTR(EventDate, 0, 5) DESC
    
    0 讨论(0)
  • 2020-12-05 04:37

    what is the type of the field EventDate, since the ordering isn't correct i assume you don't have it set to some Date/Time representing type, but a string. And then the american way of writing dates is nasty to sort

    0 讨论(0)
  • 2020-12-05 04:39

    I'm guessing EventDate is a char or varchar and not a date otherwise your order by clause would be fine.

    You can use CONVERT to change the values to a date and sort by that

    SELECT * 
    FROM 
         vw_view 
    ORDER BY 
       CONVERT(DateTime, EventDate,101)  DESC
    

    The problem with that is, as Sparky points out in the comments, if EventDate has a value that can't be converted to a date the query won't execute.

    This means you should either exclude the bad rows or let the bad rows go to the bottom of the results

    To exclude the bad rows just add WHERE IsDate(EventDate) = 1

    To let let the bad dates go to the bottom you need to use CASE

    e.g.

    ORDER BY 
        CASE
           WHEN IsDate(EventDate) = 1 THEN CONVERT(DateTime, EventDate,101)
           ELSE null
        END DESC
    
    0 讨论(0)
  • 2020-12-05 04:40

    Assuming that you have the power to make schema changes the only acceptable answer to this question IMO is to change the base data type to something more appropriate (e.g. date if SQL Server 2008).

    Storing dates as mm/dd/yyyy strings is space inefficient, difficult to validate correctly and makes sorting and date calculations needlessly painful.

    0 讨论(0)
  • 2020-12-05 04:43

    try ORDER BY MONTH(Date),DAY(DATE)

    Try this:

    ORDER BY YEAR(Date) DESC, MONTH(Date) DESC, DAY(DATE) DESC

    Worked perfectly on a JET DB.

    0 讨论(0)
提交回复
热议问题