结果集返回SQL Server 2008中的默认值

时间:2012-08-22 03:58:09

标签: sql sql-server sql-server-2008

select top 1 ROW_NUMBER() OVER (ORDER BY eventtime desc) as id,
Eventcode, eventtime as et, status from cfw.dbo.DCTBLEVENTINFO 
where MeterID = 4722 and EventTime between convert(date,'2011-10-21') 
and dateadd(day,1,convert(date,'2011-10-26')) 
and EventCode = 13

原始结果集:

id  Eventcode   et                    status
1   13        2011-10-26 15:00:00.000   1

上面的查询返回完美的结果集,但如果我使用相同的查询,如下所示,则返回错误的结果

SELECT temp.et 
  FROM (SELECT TOP 1 ROW_NUMBER() OVER (ORDER BY eventtime desc) as id,
               Eventcode, 
               eventtime as et, 
               status 
          FROM cfw.dbo.DCTBLEVENTINFO 
         WHERE MeterID = 4722 
           AND EventTime BETWEEN CONVERT(date,'2011-10-21') 
                             AND DATEADD(day,1,convert(date,'2011-10-26')) 
           AND EventCode = 13) temp 
 WHERE status = 1

以上查询的结果集:

et
------------------------
2011-10-21 21:42:00.000

它会返回其他日期。我找不到问题。

2 个答案:

答案 0 :(得分:3)

尝试将ORDER BY添加到子选择中。

这样的东西
select  temp.et 
from    (
            select  top 1 
                    ROW_NUMBER() OVER (ORDER BY eventtime desc) as id, 
                    Eventcode, 
                    eventtime as et, 
                    status 
            from    cfw.dbo.DCTBLEVENTINFO  
            where   MeterID = 4722 
            and     EventTime between convert(date,'2011-10-21') and dateadd(day,1,convert(date,'2011-10-26'))  
            and     EventCode = 13
            ORDER BY eventtime desc
        )   temp 
where   status=1

请永远记住Without ORDER BY, there is no default sort order.

此外,请记住Logical Query Processing Phases – Order of Statement Execution

  
      
  1. FROM
  2.   
  3. ON
  4.   
  5. OUTER
  6.   
  7. WHERE
  8.   
  9. GROUP BY
  10.   
  11. CUBE | ROLLUP
  12.   
  13. HAVING
  14.   
  15. 选择
  16.   
  17. DISTINCT
  18.   
  19. ORDER BY
  20.   
  21. TOP
  22.   

答案 1 :(得分:0)

select top 1 temp.et from (select ROW_NUMBER() OVER (ORDER BY eventtime desc) as id,
Eventcode, eventtime as et, status from cfw.dbo.DCTBLEVENTINFO 
where MeterID = 4722 and EventTime between convert(date,'2011-10-21') 
and dateadd(day,1,convert(date,'2011-10-26')) 
and EventCode = 13 ORDER BY eventtime desc)temp where status=1

不是仅限制子查询中的一行,而是获取完整的结果,检查状态并仅限制第一行。