SQL日期顺序更正

时间:2012-01-23 14:21:32

标签: sql

在这里处理一个SQL语句,我有一个愚蠢的问题。我有这个日期字段,吐出了几年和几个月的各种日期等。我正在尝试正确订购它们但我只按顺序获得了一个月。例如:

01-05-2012
12-30-2011
12-18-2011
11-25-2011
11-24-2011
Etc.

我的查询如下:

SELECT     TOP (100) PERCENT CONVERT(VARCHAR(10), A.tran_end_time, 110) AS Date
FROM         dbo.ttdpur040101_CT AS A INNER JOIN
                      dbo.ttdpur040101_Audit AS B ON NOT (A.tran_begin_time > B.event_time_local OR
                      A.tran_end_time < B.event_time_local) AND (A.__$operation = 2 AND B.action_id = 'IN' OR
                      (A.__$operation = 3 OR
                      A.__$operation = 4) AND B.action_id = 'UP' OR
                      A.__$operation = 1 AND B.action_id = 'DL') AND B.class_type = 'U'
WHERE     (B.server_principal_name = @Name)
GROUP BY CONVERT(VARCHAR(10), A.tran_end_time, 110)
ORDER BY Date 

我想将其显示如下:

11-24-2011
11-25-2011
12-18-2011
12-25-2011
01-08-2012
01-09-2012
etc.

由于

3 个答案:

答案 0 :(得分:1)

您按已转换为VARCHAR()的日期列进行排序。而是按原始日期列排序:

ORDER BY A.tran_end_time ASC

答案 1 :(得分:0)

那是因为日期是varchar

以这种方式尝试:

SELECT     TOP (100) PERCENT CONVERT(VARCHAR(10), A.tran_end_time, 110) AS Date
FROM         dbo.ttdpur040101_CT AS A INNER JOIN
                      dbo.ttdpur040101_Audit AS B ON NOT (A.tran_begin_time > B.event_time_local OR
                      A.tran_end_time < B.event_time_local) AND (A.__$operation = 2 AND B.action_id = 'IN' OR
                      (A.__$operation = 3 OR
                      A.__$operation = 4) AND B.action_id = 'UP' OR
                      A.__$operation = 1 AND B.action_id = 'DL') AND B.class_type = 'U'
WHERE     (B.server_principal_name = @Name)
GROUP BY CONVERT(VARCHAR(10), A.tran_end_time, 110)
ORDER BY CONVERT(DATETIME, Date, 103) ASC

答案 2 :(得分:0)

SELECT CONVERT(VARCHAR(10), [Date], 110) FROM (
    SELECT TOP (100) PERCENT DATEADD(dd, datediff(dd, 0, A.tran_end_time), 0) AS Date
    FROM dbo.ttdpur040101_CT AS A 
    INNER JOIN dbo.ttdpur040101_Audit AS B ON 
        NOT (A.tran_begin_time > B.event_time_local OR
        A.tran_end_time < B.event_time_local) AND 
        (A.__$operation = 2 AND B.action_id = 'IN' OR
            (A.__$operation = 3 OR A.__$operation = 4) AND 
            B.action_id = 'UP' OR 
            A.__$operation = 1 AND 
            B.action_id = 'DL'
        ) AND 
        B.class_type = 'U'
    WHERE     (B.server_principal_name = @Name)
    GROUP BY DATEADD(dd, datediff(dd, 0, A.tran_end_time), 0)
) t
ORDER BY [Date]

非常重要的是“四舍五入”到日期部分。转换为varchar的速度比DATEADD(dd, datediff(dd, 0, A.tran_end_time), 0)快 - 因为只是数学,SQL Server可以比varchar操作快得多。