简体   繁体   中英

Order BY SQL Short Date

I would like to order by the short date

ShortDate

20-Nov
17-Nov
29-Nov
15-Nov
7-Nov
6-Dec
25-Nov
14-Nov
9-Nov
12-Nov
5-Dec
26-Nov
28-Nov
8-Nov
1-Dec
3-Dec
23-Nov

I used

ORDER BY CAST(CAST(DATEPART(MONTH,ShortDate) AS VARCHAR(10)) + CAST(RIGHT( '0' + CAST(DAY(ShortDate) AS varchar(2)), 2) AS VARCHAR(10)) AS INT) DESC

the whole query is

SELECT  StaffAttendencecount  ,TC.ShortDate
FROM #TempStaffAttendnece  
INNER JOIN #TempCONStaffAttendnece TC
ON #TempStaffAttendnece.ShortDate = TC.ShortDate
ORDER BY CAST(CAST(DATEPART(MONTH,TC.ShortDate) AS VARCHAR(10)) + CAST(RIGHT( '0' + CAST(DAY(TC.ShortDate) AS varchar(2)), 2) AS VARCHAR(10)) AS INT) DESC

but its not working I get

Msg 241, Level 16, State 1, Line 80 Conversion failed when converting date and/or time from character string.

can any one help

You ideally should not be storing your dates as text, or, if you must, then try to use an ISO format which at least has the year, month, and day. That being said, you could form a bona-fide here and then sort on that:

SELECT ShortDate
FROM yourTable
ORDER BY TRY_CONVERT(datetime, ShortDate + '-2020');

下面演示链接的屏幕截图

Demo

But, as mentioned above, you should view this query as a short term fix until you get a chance to fix your data model and convert the ShortDate column to a proper bona fide date or timestamp column.

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