简体   繁体   English

订购 BY SQL 短日期

[英]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.消息 241,级别 16,State 1,第 80 行从字符串转换日期和/或时间时转换失败。

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.理想情况下,您不应将日期存储为文本,或者,如果必须,请尝试使用至少包含年、月和日的 ISO 格式。 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.但是,如上所述,您应该将此查询视为短期修复,直到您有机会修复数据 model 并将ShortDate列转换为正确的真实日期或时间戳列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM