简体   繁体   English

MS SQL转换日期103的订购问题

[英]MS SQL convert date 103 ordering problem

I am trying to convert a Datetime from 29/07/2011 00:00:00 this from this format to just 29/07/2011. 我正在尝试将此格式的Datetime从29/07/2011 00:00:00转换为2011年7月29日。 I do this with a SELECT statement 我使用SELECT语句执行此操作

SELECT CONVERT(nvarchar(10), thisDate, 103) As thisDate ... ORDER BY thisDate

This gives an order of something like this 这给出了这样的顺序

01/08/2011
02/08/2011
05/06/2011
08/07/2011
14/07/2011
21/06/2010
21/07/2011
23/07/2011
24/07/2011
24/07/2011

However when I use 101 or 102 formatting the results are correct and the dates are ordered correctly. 但是,当我使用101102格式时,结果是正确的,并且日期顺序正确。

You can order by field of type DATETIME. 您可以按DATETIME类型的字段排序。 In you example you need to rename the alias: 在您的示例中,您需要重命名别名:

SELECT CONVERT(nvarchar(10), thisDate, 103) As thatDate ... ORDER BY thisDate

Don't convert datetime to string - converting for display purpose should be done at client side, according to the client setup. 不要将日期时间转换为字符串-根据客户端设置,出于显示目的的转换应在客户端进行。 For ordering the resultset you should use date field directly, no need to convert it, it would be just waste of resources. 要订购结果集,您应该直接使用日期字段,而无需转换它,这只会浪费资源。

The 102 style "works" because it formats date as "yy.mm.dd" which sorts "correctly" (can be ordered as string according the same rules as dates). 102样式“有效”,因为它将日期格式设置为“ yy.mm.dd”,从而“正确”排序(可以根据与日期相同的规则以字符串形式订购)。 So does 112 ("yyyymmdd") and some others, but 101 shouldn't work as you expect (it's US format "mm/dd/yyyy"). 112 (“ yyyymmdd”)和其他一些代码也是如此,但是101不能按您期望的那样工作(美国格式为“ mm / dd / yyyy”)。

Your solution doesn't work because SQL server is trying to sort based on a text string which gets sorted alphabetically, instead of sorting by date. 您的解决方案无法正常工作,因为SQL Server尝试基于按字母顺序而不是按日期排序的文本字符串进行排序。

Try doing this to your query: 尝试对您的查询执行此操作:

SELECT CONVERT(nvarchar(10), thisDate, 103) As newDate, thisDate
FROM YourTable
ORDER BY thisDate ASC

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

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