MSSQL RowNumber在DateTime上错误的行号,它是从string生成的

时间:2014-01-15 11:03:41

标签: sql-server datetime row-number

我正在使用下面的SQL查询,我得到了意想不到的结果。就好像sql在字符串上创建一个行号而不是在DateTime上,即使我已经将生成的sstring转换为DateTime。你能帮我正确调整一下吗? 谢谢。

SQL QUERY

SELECT 
ROW_NUMBER() OVER (ORDER BY ((SELECT CAST(CAST(emd.DateOfMeasure AS DATE) AS NVARCHAR) + 
                ' ' + CAST(DATEPART(HOUR, DateOfMeasure) AS NVARCHAR) +
                ':' + CAST(DATEPART(MINUTE, DateOfMeasure) AS NVARCHAR) + ':00' AS DATETIME))) AS RowNum, 
CAST((SELECT CAST(CAST(emd.DateOfMeasure AS DATE) AS NVARCHAR) + 
                ' ' + CAST(DATEPART(HOUR, DateOfMeasure) AS NVARCHAR) +
                ':' + CAST(DATEPART(MINUTE, DateOfMeasure) AS NVARCHAR) + ':00' AS DATETIME) AS DATETIME) AS 'Date'
            from Data emd

意外结果

Index      DateTime
1   2013-10-16 00:30:00.000
2   2013-10-16 00:45:00.000
3   2013-10-16 01:00:00.000
4   2013-10-16 01:15:00.000
5   2013-10-16 01:30:00.000
6   2013-10-16 01:45:00.000
7   2013-10-16 10:00:00.000
8   2013-10-16 10:15:00.000
    .
    .
    .
45  2013-10-16 19:30:00.000
46  2013-10-16 19:45:00.000
47  2013-10-16 02:00:00.000
48  2013-10-16 02:15:00.000

1 个答案:

答案 0 :(得分:1)

如评论所示,我认为这是一个更简单的查询表达式:

SELECT 
ROW_NUMBER() OVER (
      ORDER BY DATEADD(minute,DATEDIFF(minute,0,DateOfMeasure),0)) AS RowNum, 
DATEADD(minute,DATEDIFF(minute,0,DateOfMeasure),0) AS 'Date'
from Data emd

它是否也表现出同样的陌生感?