联合的SQL Order By - DateTime字段上的随机顺序

时间:2012-06-01 08:08:28

标签: sql

我收到了大约5个工会的询问;最后我在DateTime字段上得到了一个订单(所以我100%肯定没有在varchar上订购) - 似乎订单被搞砸了,出于某种原因,任何想法?也没有可识别的模式:(

SELECT a, b, c, DateField
FROM whatever

UNION

SELECT a, b, c, DateField
FROM whatever

UNION

SELECT a, b, c, DateField
FROM whatever

Order By convert(DateTime, DateField, 111) -- The convert is just to make doubly sure about the data type

2 个答案:

答案 0 :(得分:2)

为什么不这样做(我不确定你是否真的想要使用 style 111 =日本标准= yy / mm / dd。如果使用,请更好地思考 style 103 = dd/MM/yyyy)。

select *
from
(
SELECT a, b, c, convert(DateTime, DateField, 103) as mydate FROM whatever  
UNION  
SELECT a, b, c, convert(DateTime, DateField, 103) as mydate FROM whatever  
UNION  
SELECT a, b, c, convert(DateTime, DateField, 103) as mydate FROM whatever  
)
Order By mydate

答案 1 :(得分:2)

SELECT a, b, c, DateField FROM 
(SELECT a, b, c, DateField
FROM whatever

UNION

SELECT a, b, c, DateField
FROM whatever

UNION

SELECT a, b, c, DateField
FROM whatever) x
Order By DateField