2012-08-22 69 views
1
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 

原始ResultSet的:结果集返回在SQL Server的默认值2008

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 

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

回答

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.

此外,remeber的Logical Query Processing Phases – Order of Statement Execution

  1. FROM
  2. ON
  3. OUT ER
  4. WHERE
  5. GROUP BY
  6. CUBE | ROLLUP
  7. HAVING
  8. 选择
  9. DISTINCT
  10. ORDER BY
  11. TOP
+0

感谢U - @ astander –

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 

而是在子查询限制只有一排,得到完整的结果,检查状态并单独限制第一行。