2012-08-22 66 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 

而是在子查詢限制只有一排,得到完整的結果,檢查狀態並單獨限制第一行。